Android高手之路之獲取正在執行的service,以及判斷某個service是否正在執行
阿新 • • 發佈:2019-02-05
注:本文改自http://blog.csdn.net/android_tutor/article/details/5824581
其實主要是用了activityManager的getRunningServices來獲取正在執行的service的列表。然後用正在執行的服務的名稱去比對相等。
看程式碼:
package com.example.runningservice; import java.util.List; import android.app.Activity; import android.app.ActivityManager; import android.os.Bundle; import android.widget.TextView; public class RunningService extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView mTextView = new TextView(this); ActivityManager mActivityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningServiceInfo> mServiceList = mActivityManager.getRunningServices(30); // the service name which u want to judge final String musicClassName = "com.android.launcher2.MusicService"; boolean b = MusicServiceIsStart(mServiceList, musicClassName); mTextView.setText("the service u need to judge is:"+b+"\n"+"all is:"+getServiceClassName(mServiceList)); setContentView(mTextView); } //judge the service is start private boolean MusicServiceIsStart(List<ActivityManager.RunningServiceInfo> mServiceList,String className){ for(int i=0;i<mServiceList.size();++i){ if(className.equals(mServiceList.get(i).service.getClassName())){ return true; } } return false; } // get all service name of list private String getServiceClassName(List<ActivityManager.RunningServiceInfo> mServiceList){ String res = ""; for(int i=0;i<mServiceList.size();++i){ res +=mServiceList.get(i).service.getClassName()+"\n"; } return res; } }
效果: