Android - 如何确保我的服务重新启动?

时间:2010-08-31 09:48:05

标签: android service crash restart

我有一个运行Service后台的Android应用程序。

当服务崩溃或被Android杀死时,我可以看到Android再次尝试重新启动它。

然而,服务从未真正重新开始,我可以看到Android安排重启,但实际上是新的。

我的代码如下:


@Override
public void onCreate() {
    String ns = Context.NOTIFICATION_SERVICE;
    mNotificationManager = (NotificationManager) getSystemService(ns);
    mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    audio_service = (AudioManager) getSystemService(Context.AUDIO_SERVICE);


}

// This is the old onStart method that will be called on the pre-2.0
// platform.  On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
    handleCommand(intent);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

 void handleCommand(Intent intent) {

        running = true;
        mTelephonyManager.listen(new IncomingListener(), PhoneStateListener.LISTEN_CALL_STATE);

    }

我的代码中是否缺少允许重新启动服务的内容?

1 个答案:

答案 0 :(得分:2)

您是否尝试过使用startForeground()