【发布时间】:2015-05-31 08:22:44
【问题描述】:
我想创建一个即使在应用程序被终止时仍在运行的服务,所以我创建了一个未绑定的服务,以便它不绑定到活动生命周期。但是每次我通过长按和滑动来终止应用程序时,该服务也会被终止。可以请一些帮助我。 谢谢
服务
public class MyService extends Service {
public GCMNotificationIntentService() {
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "Service binded");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "Service unbound");
return super.onUnbind(intent);
}
@Override
public void onCreate() {
Log.d(TAG, "Service created");
super.onCreate();
}
@Override
public void onDestroy() {
Log.d(TAG, "Service destoryed");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service started");
Thread readerThread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
Log.d(TAG, "Thread present");
try {
// thread to sleep for 1000 milliseconds
Thread.sleep(3000);
} catch (Exception e) {
System.out.println(e);
}
}
}
});
readerThread.start();
return super.onStartCommand(intent, flags, startId);
}
}
我从这样的活动中调用它
startService(new Intent(MyService.class.getName()));
该服务运行良好,直到应用程序处于后台或前台但当我长时间 按下并扫过应用程序,服务也会停止并显示这样的崩溃消息
计划在 1000 毫秒内重启崩溃的服务 com.net.gs.MyService
I/ActivityManager(1160):强制停止服务 ServiceRecord{44989bf0 u0 com.net.gs.MyService}
【问题讨论】:
-
当然,当你杀死一个进程时,在那个进程中运行的所有东西都会死掉。 Android 可能会(也可能不会)在新进程中重新启动某些组件。
-
我已经解决了这个问题:stackoverflow.com/questions/16651009/…
-
此外,我添加了一个函数 onDestroySubstitute(),我在取消绑定活动的 onDestroy 方法中的服务之前从 myActivity 调用该函数。在 onDestroySubstitute() 中,我使用例如准备服务以进行正确的重启。 SharedPreferences 并在那里保存我重启后需要的内容。
标签: android android-layout android-activity service