私はこのサービスを持っている場合、私はサービスからブロードキャストしたいので、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()の静的定義方法は簡単です –