如果我有这项服务,我需要创建一个方法getCoordinates(),因为我想从服务中进行广播,但是我希望这些坐标可用于需要时从活动中消费。比方说,我有一个方法getCoordinates(),这是创建一个可访问的方法来调用它的活动的最佳方式?那个电话会在想要消费它的活动中如何呢?如果服务没有启动不会导致应用程序崩溃,那么是否需要进行任何检查?我目前的代码在下面提供。非常感谢你。如何执行一个在活动中启动的服务上定义的方法并返回结果?
@SuppressWarnings("MissingPermission")
public class GPSService extends Service {
private LocationListener listener;
private LocationManager locationManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
listener= new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//To transfer the data to the main activity I use broadcast receiver in the main activity, using an intent filter location_update
Intent intentSendLocationMainActivity = new Intent("location_update");
Log.d("Location-update",location.getLongitude()+" "+location.getLongitude());
intentSendLocationMainActivity.putExtra("coordinates",location.getLongitude()+" "+location.getLongitude());
//I need to differentiate here if the app is killed or not to send the location to main activity or to a server
sendBroadcast(intentSendLocationMainActivity);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent activateGPSIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activateGPSIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activateGPSIntent);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission, listen for updates every 3 seconds
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed, Removing update location listener");
//unregistering the listener
/*if(locationManager != null){
locationManager.removeUpdates(listener);
}*/
}
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//here you can call a background network request to post you location to server when app is killed
Toast.makeText(getApplicationContext(), "Warning: App killed", Toast.LENGTH_LONG).show();
//stopSelf(); //call this method to stop the service
}
public void getCoordinate(){
//return coordinates to the user
}
}
你会创建一个可用的方法,并始终在你的应用程序?! –
是的....这是目标....为服务有一个名为“getCoordinates()”,并从整个应用程序消耗...... – Juan
你可以简单定义getCoordinate()如何静态 –