我的服务没有被销毁 - 如何停止服务

时间:2014-06-24 15:36:42

标签: android android-service

我是android新手。我想从MainActivity中停止Service。但是我没有得到它。在调用stopService()时它只显示Toast消息。我观察到服务仍在后台运行。如何停止服务。这是我的示例代码。

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // Method to start the service
    public void startService(View view) {
        startService(new Intent(getBaseContext(), MyService.class));
    }
    // Method to stop the service
    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }
}
public class MyService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    static int i=0;
    private static final String Tag="MyService";
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
        new Thread() {
            public void run() {
                while (true) {
                    Log.v(Tag,"Thread"+i);
                }
            }
        }.start()
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:1)

如果您在onDestroy中看到Toast,服务正在停止,但我认为您对日志记录的继续感到困惑。日志记录继续,因为它发生在单独的线程中。如果您想让线程停止,您可以对服务进行一些简单的更改:

public class MyService extends Service {

    private Thread mThread;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    static int i=0;
    private static final String Tag="MyService";
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
        mThread = new Thread() {
            public void run() {
                while (!interrupted()) {
                    Log.v(Tag,"Thread"+i);
                }
            }
        }.start()
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        mThread.interrupt();
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

注意使用mThread并检查循环中的interrupted()。我没有对此进行测试,但我相信它应该可行。