您如何正确终止服务,stopService() 不工作?

How do you properly terminate a Service, stopService() not working?

无法终止在 Android 中创建的服务,它在 stopService 后保持 运行ning。按如下方式启动服务:

    Intent i = new Intent(this, MyService.class);
    startService(i);

关联的清单条目:

 <service android:name=".services.MyService" ></service>

MyService 的要点将在多个活动中持续存在,因此我没有使用 IntentService:

package com.sample.app.services;

public class MyService extends Service {

public static final String TAG = MyService.class.getSimpleName();
private Handler handler;

protected void onHandleIntent(Intent intent) {


    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getBaseContext(), "MyService Intent...  Start", Toast.LENGTH_LONG).show();
        }
    });

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    handler = new Handler();

            myProcessing();

    //  This will cause the service to hang around
    return (START_STICKY);
}


@Override
public IBinder onBind(Intent intent) {
    return (null);
}

@Override
public void onDestroy() {
    super.onDestroy();

    }
}

在各种活动中甚至在 super.onDestroy() 之前在上面的 onDestroy() 中尝试过;上面我尝试了以下内容:

        Intent i = new Intent(this, MyService.class);
    stopService(i);

MyService 只是继续 运行。我相信根据定义该服务是单例。

如果你想停止服务,有两种方法可以做到,

1) 在服务 class.

中调用 stopself()

2) 使用 stopService()。

在你的情况下,说你的服务 class 在不同的包中(即使它在同一个包中也没关系)你最好为你的服务使用一个意图过滤器,这样很容易停止并启动如下服务。

<service android:name=".services.MyService" android:enabled="true">
        <intent-filter android:label="@string/myService" >
            <action   android:name="custom.MY_SERVICE"/>
        </intent-filter>
    </service>

并将其添加到您的服务中 class

public static final String ServiceIntent = "custom.MY_SERVICE"

然后您可以像下面这样启动或停止服务。

startService(new Intent(MyService.ServiceIntent));
stopService(new Intent((MyService.ServiceIntent));

希望这对您有所帮助。谢谢