2015-05-27 67 views
0

我正在使用Android中的服務。我不知道如何用服務取代這些活動方法。如何重新分配這些服務方法

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

    checkPlayServices(); 

    // Resuming the periodic location updates 
    if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { 
     startLocationUpdates(); 
    } 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (mGoogleApiClient.isConnected()) { 
     mGoogleApiClient.disconnect(); 
    } 
} 
@Override 
protected void onPause() { 
    super.onPause(); 
    stopLocationUpdates(); 
} 

請告訴我如何取代他們

+0

你不要「替換它們」。這些行爲沒有相同之處。相反,考慮到應用程序的業務邏輯和「服務」API的性質,您可以在其他有用的地方調用像checkPlayServices()這樣的方法。 – CommonsWare

回答

0

這可以幫助你從活動實現回調到您的服務在你的Activity生命週期方法

寫這篇文章。

Intent intent = new Intent(); 
intent.setAction("com.example.ON_RESUME");//change this for appropriate callback 
sendBroadcast(intent); 

變化像

class YourService extends Service { 
    @Override 
    public IBinder onBind(Intent intent) { 
     //Do your stuff 
     return null; 
    } 


    private void onResume() { 
     //do your stuff 
    } 

    private void onStop() { 
     //do your stuff 
    } 

    private void onPause() { 
     //do your stuff 
    } 

    public static class ActivityLifeCycleReceiver extends BroadcastReceiver { 

     public String ACTION_ON_RESUME = "com.example.ON_RESUME"; 
     public String ACTION_ON_STOP = "com.example.ON_STOP"; 
     public String ACTION_ON_PAUSE = "com.example.ON_PAUSE"; 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      if (ACTION_ON_PAUSE.equals(action)) { 
       onPause(); 
      } else if (ACTION_ON_RESUME.equals(action)) { 
       onResume(); 
      } else if (ACTION_ON_STOP.equals(action)) { 
       onResume(); 
      } 
     } 
    } 
} 

服務最後清單中註冊接收器。

<receiver android:name=".YourService$ActivityLifeCycleReceiver"> 
     <intent-filter > 
      <action android:name="com.example.ON_RESUME"/> 
      <action android:name="com.example.ON_STOP"/> 
      <action android:name="com.example.ON_PAUSE"/> 
     </intent-filter> 
    </receiver>