gpt4 book ai didi

android - Activity 暂停时启动服务

转载 作者:行者123 更新时间:2023-11-30 02:42:32 26 4
gpt4 key购买 nike

我正在创建一个在 map 中显示用户位置的应用程序,现在我想在应用程序处于后台时更新用户位置,特别是我想在 时启动 Service >Activity 的方法 onPause() 被调用。

我的 Activity :

public class MapsActivity extends Activity implements OnClickListener, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener, OnInfoWindowClickListener {

private static final long UPDATE_INTERVAL = 5000;
private static final long FASTEST_INTERVAL = 1000;
private GoogleMap map = null;
private LocationClient locationClient;
private Location myLocation;
private LocationRequest locationRequest;
private LatLng newPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
locationClient = new LocationClient(this, this, this);
locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL).setSmallestDisplacement(10);
if (locationClient != null)
// connect the client to the Google Play services
locationClient.connect();
}

@Override
public void onLocationChanged(Location location) {
newPosition = new LatLng(location.getLatitude(), location.getLongitude());
myLocation = location;
if (myLocation != null)
button.setClickable(true);
else
button.setClickable(false);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 20));
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
}

@Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "I'm bringing you to your area.", Toast.LENGTH_SHORT).show();
// start periodic updates
locationClient.requestLocationUpdates(locationRequest, this);
}

@Override
public void onDisconnected() {
Toast.makeText(this, "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}

public ProgressDialog getProgress() {
return progress;
}

@Override
protected void onResume() {
super.onResume();
}

@Override
protected void onStart() {
super.onStart();
}

@Override
protected void onRestart() {
super.onRestart();
}

@Override
protected void onPause() {
super.onPause();
}

@Override
protected void onStop() {
super.onStop();
}

@Override
protected void onDestroy() {
if (locationClient.isConnected() && locationClient != null) {
locationClient.removeLocationUpdates(this);
locationClient.disconnect();
}
super.onDestroy();
}

}

我的服务等级:

public class locationBackgroundService extends Service implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {

private LocationRequest mLocationRequest;
private LocationClient mLocationClient;

public locationBackgroundService() {

}

@Override
public void onCreate() {
mLocationRequest = LocationRequest.create();
// mLocationRequest.setInterval(CommonUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// mLocationRequest.setFastestInterval(CommonUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
mLocationClient = new LocationClient(getApplicationContext(), this, this);
mLocationClient.connect();
}


@Override
public void onStart(Intent intent, int startId) {
int start = Service.START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
return null;
}


@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}

@Override
public void onConnected(Bundle arg0) {
Log.i("info", "Location Client is Connected");
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Log.i("info", "Service Connect status :: " + isServicesConnected());
}

@Override
public void onDisconnected() {
Log.i("info", "Location Client is Disconnected");
}

@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}


private boolean isServicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(locationBackgroundService.this);

// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}

@Override
public void onDestroy() {
mLocationClient.removeLocationUpdates(this);
super.onDestroy();
}

}

有可能吗?

提前致谢。

最佳答案

LocationService.class 的例子

package com.example.myapp;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.example.myapp.activities.MainActivity;

public class LocationService extends Service implements
LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {

public static final String LOCATION_SERVICE = "LocationService";
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
float minDist = 100f;
int minTime = 10000;
PendingIntent contentIntent;
public static String USER_LATITUDE = "user_latitude";
public static String USER_LONGITUDE = "user_longitude";

@Override
public void onCreate() {
Log.d("onCreate", "");
super.onCreate();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(minTime);
//mLocationRequest.setSmallestDisplacement(minDist);
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient.connect();
return Service.START_NOT_STICKY;
}

@Override
public void onLocationChanged(Location location) {
float latitude = (float) location.getLatitude();
float longitude = (float) location.getLongitude();
Log.d("onLocationChanged. latLng", latitude + ", " + longitude);
Intent intent = new Intent(LOCATION_SERVICE);
intent.putExtra(USER_LATITUDE, latitude);
intent.putExtra(USER_LONGITUDE, longitude);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

@Override
public void onDestroy() {
super.onDestroy();
if (mLocationClient.isConnected() ) {
stopPeriodicUpdates();
}
}

@Override
public void onConnected(Bundle bundle) {
Log.d(LOCATION_SERVICE, "onConnected");
startPeriodicUpdates();
}

@Override
public void onDisconnected() {
Log.d(LOCATION_SERVICE, "onDisconnected");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(LOCATION_SERVICE, "onConnectionFailed");
}

public void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Log.d(LOCATION_SERVICE, "startPeriodicUpdates");
}

private void stopPeriodicUpdates() {
mLocationClient.removeLocationUpdates(this);
Log.d(LOCATION_SERVICE, "stopPeriodicUpdates");
}
}

加入MainActivity.class

private boolean servicesConnected() {
int resultCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == resultCode) {
Log.d("servicesConnected", "Google play services isConnected");
return true;
} else {
return false;
}
}

private BroadcastReceiver mLocationReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
float latitude = intent.getFloatExtra(LocationService.USER_LATITUDE, 0);
float longitude = intent.getFloatExtra(LocationService.USER_LONGITUDE, 0);
//do something
}
};

@Override
public void onPause() {
super.onPause();
Intent service = new Intent(this, LocationService.class);

IntentFilter intentLocationServiceFilter = new IntentFilter(LocationService
.LOCATION_SERVICE);
LocalBroadcastManager.getInstance(this)
.registerReceiver(mLocationReceiver, intentLocationServiceFilter);
if (servicesConnected()) {
startService(service);
}
}

并且不要忘记将您的 LocationService 添加到 AndroidManifest 文件

关于android - Activity 暂停时启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25566877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com