2016-10-24 17 views
1

如果我有这项服务,我需要创建一个方法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 
    } 
} 
+0

你会创建一个可用的方法,并始终在你的应用程序?! –

+1

是的....这是目标....为服务有一个名为“getCoordinates()”,并从整个应用程序消耗...... – Juan

+0

你可以简单定义getCoordinate()如何静态 –

回答

1

您可以定义getCoordinates()方法是如何静态方法:你

public static void getCoordinate(){ 
    //return coordinates to the user 
} 

有了这个soluction随处调用它,总是。

注意:你已经定义了getCoordinates()如何void,它不能返回任何东西。

+1

我会试试这个......看起来是这样做的完美方式......即使它是一个类级别的方法,我也可以从一个实例调用它吗? – Juan

+0

是的,你可以从GPSService类中调用它,但是正确的方法是用sintax:'GPSService.getCoordinate();' **我建议你看看例子或者阅读指南'使用静态方法,即使它在概念上非常简单** –

+0

请阅读此问题的最佳答案的第一句话:http:// stackoverflow。com/questions/2671496/java-when-to-use-static-methods _One rule-of-thumb:问问自己“调用这个方法是否合理,即使没有构造Obj?如果是这样,它肯定应该是静态的._ –

0

在您的服务中创建一个扩展Binder的类,并在此类中创建一个返回指向该服务本身的指针的函数。还可以创建你的活页夹类的同TIPE的成员变量,并在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()

+0

事情是,我需要按需使用这个活动,我有3个标签是碎片。如果我进入一个片段,我将能够检索服务的实例,如果在我解绑的活动的onPause()上?为了使它更清晰,想象一下MainActivity我有一个名为'getGPSServiceInstance()'的方法...... Activity绑定到服务 - > Activity将它存储在由getter方法返回的变量上 - > activity puts在暂停 - >活动打开(片段)包含的标签之一试图检索与getGPS的GPS实例...将工作? – Juan

+0

@Juan如果符合您的需求,您可以将活动中的所有逻辑放入片段中。你可以调用'getActivity()。bindService(...);'。您甚至可以同时绑定来自多个活动或片段的服务。 – Merlevede

相关问题