使用融合的 google api 和挂起的意图,更新位置
Posted
技术标签:
【中文标题】使用融合的 google api 和挂起的意图,更新位置【英文标题】:Using fused google api and pending intent ,updating location 【发布时间】:2016-08-28 06:14:22 【问题描述】:使用 googlelocationapi ,如何在应用处于后台时获取位置更新?
我知道为此我们必须使用 requestLocationUpdates() ,其中使用了待处理的意图。但是如何实现这一点,请详细说明所有步骤。
我使用 requestLocationUpdates 和 locationListener 的类,它只在前台更新位置
package learn2crack.marshmallowpermissions;
公共类 Go 扩展 Activity 实现 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
/* 私有类 SendData 扩展 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);
*/
【问题讨论】:
看看这个问题:***.com/questions/17827121/… 【参考方案1】:是的,您可以在使用 fusedApi 时使用待定意图在后台获取位置。
下面的链接有很好的例子。
https://codelabs.developers.google.com/codelabs/background-location-updates-android-o/#0
【讨论】:
以上是关于使用融合的 google api 和挂起的意图,更新位置的主要内容,如果未能解决你的问题,请参考以下文章
Chrome 中 JQuery 停止和挂起的 ajax 请求