我正在编写一个服务,该服务每隔一段时间就会向远程服务器发送一条消息。 我正在使用Android 4.4(KitKat)。 该服务还具有一项活动,该活动允许进行一些最少的配置,例如远程服务器的URL。
我设法使该服务正常工作,从启动开始,如果被杀死,则重新启动,但是后者存在一些问题。 如果我是第一次打开该应用程序,则一切正常。终止该应用会导致广播意图,并且服务会恢复(当然不进行任何活动)。现在,如果我第二次打开该应用程序(杀死并恢复后),下次我再次终止该应用程序时,该服务将不会重新启动。
我的广播接收器:
public class dynDNSBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "dynDNSBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Broadcast received, starting dynDNS service");
context.startService(new Intent(context, dyndns.class));
}
}
我的服务:
public class dyndns extends Service {
private static String TAG = "dynDNS service";
public SharedPreferences myPrefs;
private Handler mainHandler;
private Timer timer;
@Override
public IBinder onBind(Intent arg0) {
Log.i(TAG, "Service onBind");
return null;
}
@Override
public void onCreate() {
super.onCreate();
startForeground(1, new Notification());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "dynDNS service started");
mainHandler = new Handler(getApplicationContext().getMainLooper());
timer = new Timer();
timer.schedule(new MyTimerTask(), 10000, 10000);
return START_STICKY;
}
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
Log.d(TAG, "dynDNS service destroyed");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartService");
broadcastIntent.setClass(this, dynDNSBroadcastReceiver.class);
this.sendBroadcast(broadcastIntent);
}
我的活动中的相关代码:
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
assert manager != null;
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.d(TAG, serviceClass.getName());
Log.d (TAG, "Service status: Running");
return true;
}
}
Log.d (TAG, "Service status: Not running");
return false;
}
@Override
protected void onDestroy() {
stopService(mServiceIntent);
super.onDestroy();
}
清单上的相关代码:
<service
android:name="com.dyndns.dyndns"
android:enabled="true" android:process=":externalProcess">
<intent-filter>
<action android:name="com.dyndns.dyndns" />
</intent-filter>
</service>
<receiver android:name="dynDNSBroadcastReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="restartService"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>