Using googlelocationapi ,how to get location updates when app is in background?
I know for this we have to use requestLocationUpdates() in which pending intent is used.But how to implement this, please elaborate with all steps.
class in which i have used requestLocationUpdates with locationListener which update location only in foreground
package learn2crack.marshmallowpermissions;
public class Go extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static int REQUEST_CODE_RECOVER_PLAY_SERVICES = 200;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 22;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 20;
private TextView timel, tvl, tvla, ip;
private EditText et;
private Button btn;
public String mac;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private SQLiteDatabase db = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private com.google.android.gms.common.api.GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.go);
et = (EditText) findViewById(R.id.editText);
timel = (TextView) findViewById(R.id.time);
tvl = (TextView) findViewById(R.id.textView);
tvla = (TextView) findViewById(R.id.textView2);
ip = (TextView) findViewById(R.id.textView3);
btn = (Button) findViewById(R.id.send);
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS data(lat VARCHAR,lon VARCHAR,macAd VARCHAR,timelast varchar)");
if (checkGooglePlayServices()) {
buildGoogleApiClient();
//prepare connection request
createLocationRequest();
}
WifiManager mgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = mgr.getConnectionInfo();
mac = info.getMacAddress();
ip.setText(mac);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM data", null);
String all = "";
c.moveToFirst();
while (c.moveToNext()) {
all = all + c.getString(c.getColumnIndex("lat")) + c.getString(c.getColumnIndex("lon")) + c.getString(c.getColumnIndex("macAd")) + c.getString(c.getColumnIndex("timelast")) + "\n";
}
// db.close();
et.setText(all);
}
});
if (isNetworkAvailable()) {
Log.d("Main", "not called");
// new SendData().execute();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new com.google.android.gms.common.api.GoogleApiClient.Builder(this).addApi(com.google.android.gms.appindexing.AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//check net connectivity
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
//check for google play service
private boolean checkGooglePlayServices() {
int checkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (checkGooglePlayServices != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(checkGooglePlayServices, this, REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
return false;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_RECOVER_PLAY_SERVICES) {
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Google Play Services must be installed.", Toast.LENGTH_SHORT).show();
finish();
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this, "GPS not available", Toast.LENGTH_LONG).show();
}
/* Second part*/
@Override
protected void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
Double longi = mLastLocation.getLongitude();
Double lat = mLastLocation.getLatitude();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timelu = df.format(c.getTime());
Toast.makeText(this, "Latitude:" + mLastLocation.getLatitude() + ", Longitude:" + mLastLocation.getLongitude(), Toast.LENGTH_LONG).show();
tvl.setText(longi.toString());
tvla.setText(lat.toString());
timel.setText(timelu);
//kamal asshole's code
db.execSQL("CREATE TABLE IF NOT EXISTS data(lat VARCHAR,lon VARCHAR,macAd VARCHAR,timelast varchar)");
String lati = Double.toString(lat);
String lon = Double.toString(longi);
db.execSQL("INSERT INTO data VALUES('" + lati + "','" + lon + "','" + mac + "','" + timelu + "')");
/*String url="kamalag.esy..es/home.php?lat="+lat+"&lon="+longi+"&macid="+macAd+"&ts="+timelu;
if (!url.startsWith("https://") && !url.startsWith("http://")){
url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(openUrlIntent);*///
}
startLocationUpdates();
}
//database entry
@Override
public void onLocationChanged(Location location) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timelu = df.format(c.getTime());
mLastLocation = location;
Double longi = mLastLocation.getLongitude();
Double lat = mLastLocation.getLatitude();
Toast.makeText(this, "Update -> Latitude:" + mLastLocation.getLatitude() + ", Longitude:" + mLastLocation.getLongitude(), Toast.LENGTH_LONG).show();
db.execSQL("CREATE TABLE IF NOT EXISTS data(lat VARCHAR,lon VARCHAR,macAd VARCHAR,timelast varchar)");
String lati = Double.toString(lat);
String lon = Double.toString(longi);
db.execSQL("INSERT INTO data VALUES('" + lati + "','" + lon + "','" + mac + "','" + timelu + "')");
}
protected void stopLocationUpdates() {
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
@Override
protected void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.disconnect();
}
//asynctask class to send data in background
/* private class SendData extends AsyncTask {
@Override
protected String doInBackground(Void... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
InputStream is;
BufferedReader reader;
// Will contain the raw JSON response as a string.
StringBuilder response = null;
db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM data", null);
c.moveToFirst();
Log.d("Main", " called");
try {
while (c.moveToNext()) {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
String lat = c.getString(c.getColumnIndex("lat"));
String lon = c.getString(c.getColumnIndex("lon"));
String macid = c.getString(c.getColumnIndex("macAd"));
String ts = c.getString(c.getColumnIndex("timelast"));
Log.d("Main", "data inserted");
String urlstring = "http://kamalag.esy.es/home.php?" + "lat=" + lat + "&lon=" + lon + "&macid=" + macid + "&ts=" + ts;
URL url = new URL(urlstring);
Log.d("error", urlstring);
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
is = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
String temp;
response = new StringBuilder();
while ((temp = reader.readLine()) != null) {
response.append(temp);
}
db.execSQL("delete from data WHERE lat= '"+lat+"'and lon='"+lon+"' and macAd='"+macid+"'and timelast='"+ts+"'");
return response.toString();
}
}catch (Exception e) {
Log.d("PlaceholderFragment", "Error ");
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
c.close();
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// db.();
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}*/
}