我正在开发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 :(得分:0)
这可以帮助您通过活动实现对服务的回调
将此内容写入您的活动生命周期方法。
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();
}
}
}
}
最后在MANIFEST中注册接收器。
<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>