下面列出了怎么用android.content.pm.ServiceInfo的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 停止某个插件Service, 当全部的插件Service都停止之后, ProxyService也会停止
*
* @param targetIntent targetIntent
* @return int
*/
int stopService(Intent targetIntent) {
ServiceInfo serviceInfo = selectPluginService(targetIntent);
if (serviceInfo == null) {
Log.e(TAG, "can not found service: " + targetIntent.getComponent());
return 0;
}
Service service = mServiceMap.get(serviceInfo.name);
if (service == null) {
Log.w(TAG, "can not running, are you stopped it multi-times?");
return 0;
}
service.onDestroy();
mServiceMap.remove(serviceInfo.name);
if (mServiceMap.isEmpty()) {
// 没有Service了, 这个没有必要存在了
Log.d(TAG, "service all stopped, stop proxy");
Context appContext = MApplication.getInstance();
appContext.stopService(new Intent().setComponent(new ComponentName(appContext.getPackageName(), PluginProxyService.class.getName())));
}
return 1;
}
/**
* @return true iff a RecognitionService with the given component name is installed
*/
public static boolean isRecognitionServiceInstalled(PackageManager pm, ComponentName componentName) {
List<ResolveInfo> services = pm.queryIntentServices(
new Intent(RecognitionService.SERVICE_INTERFACE), 0);
for (ResolveInfo ri : services) {
ServiceInfo si = ri.serviceInfo;
if (si == null) {
Log.i("serviceInfo == null");
continue;
}
if (componentName.equals(new ComponentName(si.packageName, si.name))) {
return true;
}
}
return false;
}
/**
* @return A mocked context which returns a spy of {@link RuntimeEnvironment#application} in
* {@link Context#getApplicationContext()}.
*/
public static Context createMockContext() {
// otherwise the JobScheduler isn't supported we check if the service is enabled
// Robolectric doesn't parse services from the manifest, see https://github.com/robolectric/robolectric/issues/416
PackageManager packageManager = mock(PackageManager.class);
when(packageManager.queryBroadcastReceivers(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(new ResolveInfo()));
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = new ServiceInfo();
resolveInfo.serviceInfo.permission = "android.permission.BIND_JOB_SERVICE";
when(packageManager.queryIntentServices(any(Intent.class), anyInt())).thenReturn(Collections.singletonList(resolveInfo));
Context context = spy(ApplicationProvider.getApplicationContext());
when(context.getPackageManager()).thenReturn(packageManager);
when(context.getApplicationContext()).thenReturn(context);
Context mockContext = mock(MockContext.class);
when(mockContext.getApplicationContext()).thenReturn(context);
return mockContext;
}
public ServiceInfo getServiceInfo(ComponentName className, int flags) throws NameNotFoundException, RemoteException {
ServiceInfo serviceInfo = null;
if (className != null) {
try {
if (!(this.mApkManager == null || className == null)) {
serviceInfo = this.mApkManager.getServiceInfo(className, flags);
}
} catch (RemoteException e) {
JLog.log("wuxinrong", "获取svervice信息 失败 e=" + e.getMessage());
throw e;
} catch (Exception e2) {
JLog.log("wuxinrong", "获取svervice信息 失败 e=" + e2.getMessage());
}
}
return serviceInfo;
}
private static ResolveInfo newResolveInfo(ServiceInfo serviceInfo, IntentFilter intentFilter) {
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.serviceInfo = serviceInfo;
resolveInfo.filter = intentFilter;
resolveInfo.resolvePackageName = serviceInfo.packageName;
resolveInfo.labelRes = serviceInfo.labelRes;
resolveInfo.icon = serviceInfo.icon;
resolveInfo.specificIndex = 1;
// if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
// 默认就是false,不用再设置了。
// resolveInfo.system = false;
// }
resolveInfo.priority = intentFilter.getPriority();
resolveInfo.preferredOrder = 0;
return resolveInfo;
}
void dumpServicePermissions(PrintWriter pw, DumpState dumpState, String packageName) {
if (dumpState.onTitlePrinted()) pw.println();
pw.println("Service permissions:");
final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
while (filterIterator.hasNext()) {
final ServiceIntentInfo info = filterIterator.next();
final ServiceInfo serviceInfo = info.service.info;
final String permission = serviceInfo.permission;
if (permission != null) {
pw.print(" ");
pw.print(serviceInfo.getComponentName().flattenToShortString());
pw.print(": ");
pw.println(permission);
}
}
}
@Override
public ServiceInfo getServiceInfo(ComponentName className, int flags)
throws NameNotFoundException {
final int userId = getUserId();
try {
ServiceInfo si = mPM.getServiceInfo(className,
updateFlagsForComponent(flags, userId, null), userId);
if (si != null) {
return si;
}
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
throw new NameNotFoundException(className.toString());
}
@Override
public IBinder peekService(Intent service, String resolvedType, int userId) {
synchronized (this) {
ServiceInfo serviceInfo = resolveServiceInfo(service, userId);
if (serviceInfo == null) {
return null;
}
ServiceRecord r = findRecordLocked(userId, serviceInfo);
if (r != null) {
ServiceRecord.IntentBindRecord boundRecord = r.peekBinding(service);
if (boundRecord != null) {
return boundRecord.binder;
}
}
return null;
}
}
@Override
public ServiceInfo selectStubServiceInfoByIntent(Intent intent) throws RemoteException {
ServiceInfo ai = null;
if (intent.getComponent() != null) {
ai = getServiceInfo(intent.getComponent(), 0);
} else {
ResolveInfo resolveInfo = resolveIntent(intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), 0);
if (resolveInfo.serviceInfo != null) {
ai = resolveInfo.serviceInfo;
}
}
if (ai != null) {
return selectStubServiceInfo(ai);
}
return null;
}
private static ComponentName findRecognizerByPackage(final Context context, final String prefPackage) {
final PackageManager pm = context.getPackageManager();
final List<ResolveInfo> available = pm != null ? pm.queryIntentServices(new Intent(RecognitionService.SERVICE_INTERFACE), 0) : new LinkedList<ResolveInfo>();
final int numAvailable = available.size();
if (numAvailable == 0) {
// no available voice recognition services found
return null;
} else {
if (prefPackage != null) {
for (final ResolveInfo anAvailable : available) {
final ServiceInfo serviceInfo = anAvailable.serviceInfo;
if (serviceInfo != null && prefPackage.equals(serviceInfo.packageName)) {
return new ComponentName(serviceInfo.packageName, serviceInfo.name);
}
}
}
// Do not pick up first available, but use default one
return null;
}
}
ServiceRecord(ActivityManagerService ams,
BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
Runnable restarter) {
this.ams = ams;
this.stats = servStats;
this.name = name;
shortName = name.flattenToShortString();
this.intent = intent;
serviceInfo = sInfo;
appInfo = sInfo.applicationInfo;
packageName = sInfo.applicationInfo.packageName;
processName = sInfo.processName;
permission = sInfo.permission;
exported = sInfo.exported;
this.restarter = restarter;
createRealTime = SystemClock.elapsedRealtime();
lastActivity = SystemClock.uptimeMillis();
userId = UserHandle.getUserId(appInfo.uid);
createdFromFg = callerIsFg;
}
public String getExportedServices() {
StringBuilder sb = new StringBuilder();
if (mPInfo.services != null) {
for (ServiceInfo si : mPInfo.services) {
if (si.exported) {
if (si.permission != null) {
sb.append(si.name + " PERM: " + si.permission + "\n");
} else {
sb.append(si.name + "\n");
}
}
}
} else {
sb.append(" -- null");
}
return sb.toString();
}
public ServiceInfo resolveServiceInfo(Intent intent, int flags) throws RemoteException {
try {
if (this.mApkManager == null) {
return null;
}
if (intent.getComponent() != null) {
return this.mApkManager.getServiceInfo(intent.getComponent(), flags);
}
ResolveInfo resolveInfo = this.mApkManager.resolveIntent(intent, intent.resolveTypeIfNeeded(this.mHostContext.getContentResolver()), flags);
if (resolveInfo == null || resolveInfo.serviceInfo == null) {
return null;
}
return resolveInfo.serviceInfo;
} catch (RemoteException e) {
JLog.log("wuxinrong", "获取ServiceInfo 失败 e=" + e.getMessage());
throw e;
} catch (Exception e2) {
JLog.log("wuxinrong", "获取ServiceInfo 失败 e=" + e2.getMessage());
return null;
}
}
private static ServiceInfo replaceFirstServiceIntentOfArgs(Object[] args) throws RemoteException {
int intentOfArgIndex = findFirstIntentIndexInArgs(args);
if (args != null && args.length > 1 && intentOfArgIndex >= 0) {
Intent intent = args[intentOfArgIndex];
ServiceInfo serviceInfo = resolveService(intent);
if (serviceInfo != null && isPackagePlugin(serviceInfo.packageName)) {
ServiceInfo proxyService = selectProxyService(intent);
if (proxyService != null) {
Intent newIntent = new Intent();
newIntent.setClassName(proxyService.packageName, proxyService.name);
newIntent.putExtra(ApkConstant.EXTRA_TARGET_INTENT, intent);
args[intentOfArgIndex] = newIntent;
return serviceInfo;
}
}
}
return null;
}
static ServiceInfo getServiceInfoOrThrow(ComponentName comp, int userHandle)
throws PackageManager.NameNotFoundException {
try {
ServiceInfo si = AppGlobals.getPackageManager().getServiceInfo(comp,
PackageManager.GET_META_DATA
| PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE
| PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
userHandle);
if (si != null) {
return si;
}
} catch (RemoteException e) {
}
throw new PackageManager.NameNotFoundException(comp.toString());
}
private Bundle getMetadata(Context context) {
try {
PackageManager manager = context.getPackageManager();
if (manager == null) {
Log.w(TAG, "Context has no PackageManager.");
return null;
}
ServiceInfo info =
manager.getServiceInfo(
new ComponentName(context, discoveryService), PackageManager.GET_META_DATA);
if (info == null) {
Log.w(TAG, discoveryService + " has no service info.");
return null;
}
return info.metaData;
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, "Application info not found.");
return null;
}
}
@Override
public void take(AppDiscoveryCallbacks callbacks) {
List<ResolveInfo> resolveInfos = getResolveInfos();
if (resolveInfos == null) {
// b/32122408
return;
}
for (ResolveInfo info : resolveInfos) {
ServiceInfo serviceInfo = info.serviceInfo;
String packageName = serviceInfo.packageName;
ComponentName name = new ComponentName(packageName, serviceInfo.name);
Intent intent = new Intent();
intent.setComponent(name);
if (versionCheck(packageName)) {
final ServiceConnection conn =
makeServiceConnection(connections, name, callbacks, serviceInfo.metaData);
connections.put(packageName, conn);
context.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
}
// TODO: need to figure out when to call onDiscovery done (after every service we know
// about has connected or timed out).
}
/**
* @return true iff a RecognitionService with the given component name is installed
*/
public static boolean isRecognitionServiceInstalled(PackageManager pm, ComponentName componentName) {
List<ResolveInfo> services = pm.queryIntentServices(
new Intent(RecognitionService.SERVICE_INTERFACE), 0);
for (ResolveInfo ri : services) {
ServiceInfo si = ri.serviceInfo;
if (si == null) {
Log.i("serviceInfo == null");
continue;
}
if (componentName.equals(new ComponentName(si.packageName, si.name))) {
return true;
}
}
return false;
}
@Override
protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, int match) {
final PackageParser.Service service = filter.service;
ServiceInfo si = PackageParserCompat.generateServiceInfo(service, mFlags);
if (si == null) {
return null;
}
final ResolveInfo res = new ResolveInfo();
res.serviceInfo = si;
if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
res.filter = filter;
}
res.priority = filter.getPriority();
res.preferredOrder = service.owner.mPreferredOrder;
res.match = match;
res.isDefault = filter.hasDefault;
res.labelRes = filter.labelRes;
res.nonLocalizedLabel = filter.nonLocalizedLabel;
res.icon = filter.icon;
return res;
}
/**
* @return list of currently installed RecognitionService component names flattened to short strings
*/
public List<String> getServices(PackageManager pm) {
List<String> services = new ArrayList<>();
int flags = 0;
//int flags = PackageManager.GET_META_DATA;
List<ResolveInfo> infos = pm.queryIntentServices(
new Intent(RecognitionService.SERVICE_INTERFACE), flags);
for (ResolveInfo ri : infos) {
ServiceInfo si = ri.serviceInfo;
if (si == null) {
Log.i("serviceInfo == null");
continue;
}
String pkg = si.packageName;
String cls = si.name;
// TODO: process si.metaData
String component = (new ComponentName(pkg, cls)).flattenToShortString();
if (!mCombosExcluded.contains(component)) {
services.add(component);
}
}
return services;
}
@Override
public ServiceInfo getServiceInfo(ComponentName className, int flags) throws RemoteException {
waitForReadyInner();
try {
String pkg = getAndCheckCallingPkg(className.getPackageName());
if (pkg != null) {
enforcePluginFileExists();
PluginPackageParser parser = mPluginCache.get(className.getPackageName());
if (parser != null) {
return parser.getServiceInfo(className, flags);
}
}
} catch (Exception e) {
handleException(e);
}
return null;
}
/**
* Boring view inflation / creation
*/
private View getServicesView(ViewGroup viewGroup, View convertView, int index) {
ViewHolder viewHolder;
if (!checkIfConvertViewMatch(convertView, SERVICES)) {
convertView = mLayoutInflater.inflate(R.layout.detail_activities, viewGroup, false);
viewHolder = new ViewHolder();
viewHolder.currentViewType = SERVICES;
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.icon);
viewHolder.textView1 = (TextView) convertView.findViewById(R.id.label);
viewHolder.textView2 = (TextView) convertView.findViewById(R.id.name);
viewHolder.textView3 = (TextView) convertView.findViewById(R.id.launchMode);
convertView.findViewById(R.id.taskAffinity).setVisibility(View.GONE);
convertView.findViewById(R.id.orientation).setVisibility(View.GONE);
convertView.findViewById(R.id.softInput).setVisibility(View.GONE);
convertView.findViewById(R.id.launch).setVisibility(View.GONE);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final ServiceInfo serviceInfo = mPackageInfo.services[index];
convertView.setBackgroundColor(index % 2 == 0 ? mColorGrey1 : mColorGrey2);
//Label
viewHolder.textView1.setText(serviceInfo.loadLabel(mPackageManager));
//Name
viewHolder.textView2.setText(serviceInfo.name.replaceFirst(mPackageName, ""));
//Icon
viewHolder.imageView.setImageDrawable(serviceInfo.loadIcon(mPackageManager));
//Flags
viewHolder.textView3.setText(getString(R.string.flags) + ": " + Utils.getServiceFlagsString(serviceInfo.flags));
return convertView;
}
/**
* 选择匹配的ServiceInfo
*
* @param pluginIntent 插件的Intent
* @return ServiceInfo
*/
private ServiceInfo selectPluginService(Intent pluginIntent) {
for (ComponentName componentName : mServiceInfoMap.keySet()) {
if (componentName.equals(pluginIntent.getComponent())) {
return mServiceInfoMap.get(componentName);
}
}
return null;
}
/**
* Check to see if a component is exported
* @param context object used to retrieve the package manager
* @param name of the component in question
* @return true if this component is tagged as exported
*/
public static boolean isServiceExported(Context context, ComponentName name) {
try {
ServiceInfo serviceInfo = context.getPackageManager().getServiceInfo(name, PackageManager.GET_META_DATA);
return serviceInfo.exported;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
@Override
public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, int userId) {
checkUserId(userId);
ComponentName comp = intent.getComponent();
if (comp == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ServiceInfo si = getServiceInfo(comp, flags, userId);
if (si != null) {
final ResolveInfo ri = new ResolveInfo();
ri.serviceInfo = si;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mServices.queryIntent(intent, resolvedType, flags);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services);
}
return null;
}
}
private static boolean p(Context context, String str) {
try {
ServiceInfo serviceInfo = context.getPackageManager().getServiceInfo(new ComponentName(context.getPackageName(), str), 128);
new StringBuilder(z[13]).append(serviceInfo.processName);
z.a();
if (serviceInfo.processName.contains(context.getPackageName() + NetworkUtils.DELIMITER_COLON)) {
return true;
}
} catch (NameNotFoundException e) {
} catch (NullPointerException e2) {
new StringBuilder(z[12]).append(str);
z.a();
}
return false;
}
@Override
public ServiceInfo getServiceInfo(ComponentName className, int flags)
throws NameNotFoundException {
try {
ServiceInfo si = mPM.getServiceInfo(className, flags);
if (si != null) {
return si;
}
} catch (RemoteException e) {
throw new RuntimeException("Package manager has died", e);
}
throw new NameNotFoundException(className.toString());
}
public static String getServiceLabel(Context context, ComponentName recognizerComponentName) {
String recognizer = "[?]";
PackageManager pm = context.getPackageManager();
if (recognizerComponentName != null) {
try {
ServiceInfo si = pm.getServiceInfo(recognizerComponentName, 0);
recognizer = si.loadLabel(pm).toString();
} catch (PackageManager.NameNotFoundException e) {
// ignored
}
}
return recognizer;
}
public static boolean initialize(Context context) {
if (!SpeechRecognizer.isRecognitionAvailable(context))
return false;
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(RecognitionService.SERVICE_INTERFACE);
final List<ResolveInfo> list = pm.queryIntentServices(intent, PackageManager.GET_SERVICES);
for (ResolveInfo resolve : list) {
ServiceInfo service = resolve.serviceInfo;
if (!service.packageName.equals(PROVIDER_PACKAGE_NAME))
continue;
int versionCode;
try {
versionCode = pm.getPackageInfo(service.packageName, 0).versionCode;
} catch (NameNotFoundException e) {
continue;
}
if (versionCode < PROVIDER_MIN_VERSION)
continue;
mRecognitionProvider = new ComponentName(service.packageName, service.name);
return true;
}
// If we reach this point, we failed to find a suitable recognition provider.
return false;
}
@Override
protected boolean allowFilterResult(
PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
ServiceInfo filterSi = filter.service.info;
for (int i = dest.size() - 1; i >= 0; --i) {
ServiceInfo destAi = dest.get(i).serviceInfo;
if (destAi.name == filterSi.name
&& destAi.packageName == filterSi.packageName) {
return false;
}
}
return true;
}