安卓服务不会停止
问题描述:
我正在实施一个名为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();
}
一切工作正常,当我点击停止按钮只有服务不会停止,为什么呢?我可以告诉服务不会停止,因为在我停止服务之后,当我复制某些内容时,意图仍然会弹出。
答
从在这一点上谷歌文档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");
}
你不删除原始片段更改侦听器。这实际上是一个内存泄漏。 – DeeV
@DeeV我尝试在'onDestroy()'中将它设置为null,但是我得到了'NullPointerException' – Newbie
保存对使用'addPrimaryClipChangeListener'放入的Listener的引用,然后使用'removePrimaryClipChangedListener(ClipboardManager.OnPrimaryClipChangedListener) ' – DeeV