這可以幫助你從活動實現回調到您的服務在你的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>
你不要「替換它們」。這些行爲沒有相同之處。相反,考慮到應用程序的業務邏輯和「服務」API的性質,您可以在其他有用的地方調用像checkPlayServices()這樣的方法。 – CommonsWare