Determine whether the Service is running in the Activity. activityservice
I am studying Android and wrote a Demo. I need to start the service in an Activity. I feel that I should judge whether the service is running before it is started. Baidu has the following code to stay for backup.
<Pre name = "code" class = "java"> // This method is used to determine your own Service --> com. android. controlAddFunctions. whether PhoneService has run public static boolean isWorked () {ActivityManager myManager = (ActivityManager) context. getSystemService (Context. ACTIVITY_SERVICE); ArrayList <RunningServiceInfo> runningService = (ArrayList <RunningServiceInfo>) myManager. getRunningServices (30); for (int I = 0; I <runningService. size (); I ++) {if (runningService. get (I ). service. getClassName (). toString (). equals ("com. android. controlAddFunctions. phoneService ") {return true ;}} return false ;}
Source code
How can I determine whether the backend service is bound and running?
You can use the method on the second floor. In fact, the service has already been started and will not be started again. view the original post>
Android determines whether the service is running
Obtain all running services and make judgments. If it is your own service, you can set an identifier in advance to directly identify the identifier;
Get all running services:
PackageManager pm = contex. getPackageManager ();
ActivityManager am = (ActivityManager) contex. getSystemService (ACTIVITY_SERVICE );
// Obtain the PackageInfo object of all packages installed by the system.
List <PackageInfo> packs = pm. getInstalledPackages (0 );
List <ActivityManager. RunningServiceInfo> listSer = am. getRunningServices (30 );
// Obtain the Running Service
For (PackageInfo p: packs ){
HashMap <String, Object> map2 = new HashMap <String, Object> ();
For (ActivityManager. RunningServiceInfo ra: listSer ){
If (ra. process. equals (p. applicationInfo. packageName )){
// Obtain the memory of the process
Int [] myMempid = new int [] {ra. pid };
Debug. MemoryInfo [] memoryInfo = am
. GetProcessMemoryInfo (myMempid );
Int memSize = memoryInfo [0]. dalvikPrivateDirty;
Map2.put ("size", "memory:" + memSize + "kb ");
Map2.put ("icon", p. applicationInfo. loadIcon (pm); // icon
Map2.put ("appName", p. applicationInfo. loadLabel (pm); // Application name
Map2.put ("packageName", "package name :"
+ P. applicationInfo. packageName); // application package name
System. out. println ("pi. applicationInfo. packageName =" + p. applicationInfo. packageName );
Items. add (map2 );
}
}
}... Remaining full text>