Stop or kill a service

ε祈祈猫儿з 提交于 2020-01-12 03:51:05

问题


I am developing a task manager application..

In that app, I display to the user a list of running apps and kill button beside each app. When user presses kill button the corresponding activity will be killed and i used

      activitymanager.killbackgroundprocesses(packageName)

I created another application called service notification where user can start and stop a service by clicking on button "start service" and button "stop service" respectively.. Then before running my task manager app, i started the service from service notification app. So this activity was displayed in my task manager app.

But when i kill that activity, it disappears from the list and then appears again because the service is restarting..How do I kill the sevice then?

I used startService and onCreate for starting service and showing some notification and stopService and onDestroy for stopping service...


回答1:


I finally found an answer to my question...

After using

activitymanager.killbackgroundprocesses(packageName) , 

we have to check if there are any services running under that package name or process name.

Then we have to use

stopService(new Intent().setComponent(serviceInfos.get(i).service))

But it would return an error because android does not allow us to stop another service

So I used these two lines in the manifest and then ran my app in the build machine

coreApp="true" 
android:sharedUserId="android.uid.system"

These two lines are there in the android settings manifest file, which allows settings to stop service if the user wants.

So the activity got killed along with the service... :)

And remember this worked only on the build machine....




回答2:


Try To Use this permission in your android Manifest File.

 <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />

and Look at this link it may be helpfull... http://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29

and this: Start a service on onClick



来源:https://stackoverflow.com/questions/9389407/stop-or-kill-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!