android服务不会停止

时间:2016-11-21 02:13:30

标签: android service

我正在实现一个名为Clipboard.class的服务,当用户复制/剪切某些东西时会弹出一个意图。单击按钮时,我会从MainActivity.java运行并停止服务。

@OnClick(R.id.btn)
public void runService()
{
    Intent service = new Intent(this, Clipboard.class);
    run = Clipboard.running == 1 ? true:false;
    if(!run)
    {
        startService(service);
        btn.setText("Tap to stop");
    }
    else
    {
        stopService(service);
        btn.setText("Tap to run");
    }
}

这是我的服务Clipboard.class

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    running = 1;
    Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
    mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    mCM.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener()
    {
        @Override
        public void onPrimaryClipChanged() {
            String newClip = mCM.getText().toString();
            Toast.makeText(getApplicationContext(), newClip.toString(),  Toast.LENGTH_LONG).show();

            Intent dialogIntent = new Intent(Clipboard.this, ShareTo.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
        }
    });
    return mStartMode;
}

@Override
public void onDestroy()
{
    running = 0;
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    super.onDestroy();
}

一切正常,只有当我点击停止按钮时服务不会停止,为什么?我可以说服务没有停止,因为在我停止服务后,当我复制某些内容时,意图仍然会弹出。

1 个答案:

答案 0 :(得分:0)

来自Google文档Android Service

此服务将在此时继续运行,直到调用Context.stopService()或stopSelf()。

所以像这样使用

Intent service = new Intent(this, Clipboard.class);
run = Clipboard.running == 1 ? true:false;
if(!run)
{
    startService(service);
    btn.setText("Tap to stop");
}
else
{
    context.stopService(service);
    btn.setText("Tap to run");
}