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

发布于 2024-09-16 15:12:08 字数 1205 浏览 4 评论 0原文

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

    }

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

I have an Android application with a background running Service.

When the Service crashes or gets killed by Android I can see that Android tries to restart it again.

However the Service never actually restarts, I can see Android scheduling the restart but it new actually happens.

My code is as follows:


@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);

    }

Is there something missing in my code to allow the Service be restarted?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秉烛思 2024-09-23 15:12:08

您是否尝试过使用 <代码>startForeground()

Have you tried using startForeground()?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文