【问题标题】:Android - how to make sure my Service is restarted?Android - 如何确保我的服务重新启动?
【发布时间】:2010-08-31 09:48:04
【问题描述】:

我有一个后台运行服务的 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);

    }

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

【问题讨论】:

    标签: android service crash restart


    【解决方案1】:

    您是否尝试过使用startForeground()

    【讨论】:

    • 是的,我实现了它,它给了我一些非常奇怪的行为,即使应用程序和服务不应该运行,它也会弹出通知。问题是我尝试了一个空的 onStart() 方法,服务似乎重新启动正常。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多