需求
安卓除了系统运行的Service,安装的APP也会提供各种各样的服务,如果我们想判断某个APP正在运行的Service有哪些,由于没有源码,除了使用ADB的方式,还可以可以采用下面两种方法
方法一(不推荐):ActivityManager.getRunningServices
不推荐的原因是安卓官方已经在API 26中废弃该用法了,只可以获取到部分正在运行的服务:
This method was deprecated in API level 26. As of Build.VERSION_CODES.O , this method is no longer available to third party applications. For backwards compatibility, it will still return the caller's own services.
Return a list of the services that are currently running.
Note: this method is only intended for debugging or implementing service management type user interfaces.
如果想用,简单用法如下:
ActivityManager activityManager = (ActivityManager) yourContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceInfos = activityManager.getRunningServices(Integer.MAX_VALUE);
for (int i = 0; i < serviceInfos.size(); i++) {
Log.d(TAG, "Service name: " + serviceInfos.get(i).service.getClassName());
}
方法二(推荐):getPackageManager().queryIntentServices
我这里是获取特定APP的服务,需要知道自己安装的APP的包名是什么,如果不想设置特定包名也是可以的,在serviceIntent里设置不同的参数就可以得到不同的效果:
Intent serviceIntent = new Intent();
String[] packageNames = {"com.tencent.qqmusic", "com.baidu.netdisk", "com.kugou.android", "com.apple.android.music", "com.spotify.music"};
for (String pkgName : packageNames) {
serviceIntent.setPackage(pkgName);
List<ResolveInfo> resolveInfos = yourContext.getPackageManager().queryIntentServices(serviceIntent, 0);
Log.d(TAG, "Package: " + pkgName);
for (ResolveInfo resolveInfo : resolveInfos) {
Log.d(TAG, "Intent service name: " + resolveInfo.serviceInfo);
}
}