应用程序崩溃时如何停止服务

时间:2014-12-01 17:47:02

标签: android service notifications

我正在制作一个下载文件集的应用程序。所以我启动了一个连续下载文件的服务,以便通知也代表当前的下载状态,我的问题是应用程序崩溃时。通知不会被解雇,并且服务仍然在后台运行。我试图停止服务的服务,但它对我不起作用,请帮帮我

2 个答案:

答案 0 :(得分:0)

从文档中: http://developer.android.com/guide/components/services.html#Stopping

  

已启动的服务必须管理自己的生命周期。也就是说,系统   除非必须恢复系统,否则不会停止或销毁服务   在onStartCommand()之后内存和服务继续运行   回报。因此,服务必须通过调用stopSelf()或来自行停止   另一个组件可以通过调用stopService()来阻止它。

示例:

1-工作完成后致电stopSelf()

public class MyService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Use a Thread to not block your UI when doing operations over the network.
        // See http://developer.android.com/reference/android/app/Service.html for more information.
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadSetOfFiles();
                stopSelf();
            }
        }).start();
        return START_NOT_STICKY;
    }
}

2-手动呼叫stopService()

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        mView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(MyActivity.this, MyService.class));
                // Note: If clients are bound to the service, 
                // then the service will only stop after all clients are unbound.
            }
        });
    }
}

如果由于您的应用程序崩溃而无法手动停止服务,则在下载文件的操作结束后,通过调用stopSelf(),服务需要自行停止。

答案 1 :(得分:-1)

也许你可以通过在MainActivity onDestroy方法上销毁它来解决这个问题?所以,当你的应用程序崩溃时,它将停止服务。

相关问题