Java 如何执行';在活动中启动的服务上定义了,并返回结果?
如果我有这个服务,我需要创建一个getCoordinates()方法,因为我想从服务中广播,但我希望这些坐标在需要时可以从活动中使用。假设我有一个方法getCoordinates(),这是为活动创建可访问方法来调用它的最佳方法?这个调用在想要使用它的活动中会是怎样的?。如果服务未启动,则需要进行任何检查,以防应用程序崩溃?。下面提供了我当前的代码。多谢各位Java 如何执行';在活动中启动的服务上定义了,并返回结果?,java,android,android-service,Java,Android,Android Service,如果我有这个服务,我需要创建一个getCoordinates()方法,因为我想从服务中广播,但我希望这些坐标在需要时可以从活动中使用。假设我有一个方法getCoordinates(),这是为活动创建可访问方法来调用它的最佳方法?这个调用在想要使用它的活动中会是怎样的?。如果服务未启动,则需要进行任何检查,以防应用程序崩溃?。下面提供了我当前的代码。多谢各位 @SuppressWarnings("MissingPermission") public class GPSService exte
@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
}
}
在您的服务中创建一个扩展绑定器的类,并在此类中创建一个返回指向服务本身的指针的函数。还可以创建与Binder类相同类型的成员变量,并在
onBind()
中返回此对象。。。所有这些都在你的服务范围内
private final IBinder mBinder = new GPSBinder();
public class GPSBinder extends Binder {
public GPSService getService() {
return GPSService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
在您的活动中,您需要添加一个GPSServie类型的变量,并绑定到服务,可能是在您的onResume()
中,并添加一个ServiceConnection
对象,该对象将在绑定完成时收到通知,您将获得一个绑定器实例,您可以使用它来获取服务实例
GPSService mService;
bindService(intent, mConnection, Context.BIND_AUTO_CREATE); // Put this in onResume()
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
GPSService.GPSBinder binder = (GPSService.GPSBinder)service;
myService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mService = null;
}
};
最后,每当需要调用getCoordinate()时,只需使用服务变量
if (myService!=null)
myService.getCoordinate(); // YEAH!!!!!
不要忘记在
onPause()上解除与服务的绑定。
您可以定义getCoordinates()方法静态方法:
public static void getCoordinate(){
//return coordinates to the user
}
有了这个解决方案,你可以在任何地方、任何时候都称之为解决方案
注意:您已经定义了getCoordinates()如何为void,它不能返回任何内容
你会创建一个在你的应用程序中随处可用的方法吗?!是的……这就是目标……为了让服务有一个名为“getCoordinates()”的方法,并从整个应用程序中使用……你可以简单地定义getCoordinate(),事情是这样的,在我需要按需使用此方法的活动中,我有3个选项卡,它们是片段。如果我进入一个片段,如果在活动的onPause()上解除绑定,我是否能够检索该服务的实例?为了更清楚,假设在MainActivity上有一个名为“getGPSServiceInstance()”的方法。。。。。。活动绑定到服务-->活动将其存储在getter方法返回的变量上-->活动暂停-->活动中包含的一个选项卡打开(片段)尝试使用getGPS检索gps实例。。。这行得通吗?@Juan如果符合您的需要,您可以将活动中的所有逻辑放在一个片段中。调用
getActivity().bindService(…)代码>。您甚至可以同时从多个活动或片段绑定到服务。我一定会尝试这样做……这似乎是一种完美的方式……即使是类级方法,我也可以从实例调用它吗?是的,您可以从GPSService类的远程调用它,但正确的方法是使用sintax:GPSService.getCoordinate();代码>我建议您查看示例或阅读“静态方法的使用,即使在概念上非常简单”的指南阅读这个问题最重要答案的第一句话:一条经验法则:问问自己“即使尚未构建Obj,调用此方法是否有意义?”如果是,它肯定应该是静态的。是的,在这种情况下,这完全是有道理的,因为这是目标责任,不会有超过一个实例,而且它必须从任何地方消耗掉……我会在下班回家后尽快实施,并给出反馈!