android.content.pm.ServiceInfo Java Examples

The following examples show how to use android.content.pm.ServiceInfo. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComponentDiscovery.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #2
Source File: BaseJobManagerTest.java    From android-job with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #3
Source File: RecognitionServiceManager.java    From AlexaAndroid with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #4
Source File: ApkManager.java    From letv with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: IntentMatcher.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
    }
 
Example #6
Source File: ComponentResolver.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #7
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source File: IPluginManagerImpl.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: VActivityManagerService.java    From container with GNU General Public License v3.0 6 votes vote down vote up
@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;
    }
}
 
Example #10
Source File: IPluginManagerImpl.java    From DroidPlugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #11
Source File: RecognizerChecker.java    From dialogflow-android-client with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #12
Source File: RecognitionServiceManager.java    From speechutils with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #13
Source File: PackageDetail.java    From Inspeckage with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #14
Source File: ApkManager.java    From letv with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #15
Source File: VPackageManagerService.java    From container with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: IActivityManagerHookHandle.java    From letv with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #17
Source File: ServiceRecord.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: RecognitionServiceManager.java    From AlexaAndroid with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #19
Source File: ServiceManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * 停止某个插件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;
}
 
Example #20
Source File: ScalarSensorServiceFinder.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@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).
}
 
Example #21
Source File: VoiceInteractionServiceInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #22
Source File: ServcesManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public IBinder onBind(Context context, Intent intent) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        Service service = mNameService.get(info.name);
        if (service == null) {
            handleCreateServiceOne(context, intent, info);
        }
        return handleOnBindOne(targetIntent);
    }
    return null;
}
 
Example #23
Source File: RouterServiceValidator.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the package name for the component name
 * @param cn
 * @param pm
 * @return
 */
private String appPackageForComponentName(ComponentName cn,PackageManager pm ){
	if(cn!=null && pm!=null){
		ServiceInfo info;
		try {
			info = pm.getServiceInfo(cn, 0);
			return info.applicationInfo.packageName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	return null;
	
}
 
Example #24
Source File: RecognitionServiceManager.java    From speechutils with Apache License 2.0 5 votes vote down vote up
public static String getServiceLabel(Context context, ComponentName recognizerComponentName) {
    try {
        PackageManager pm = context.getPackageManager();
        ServiceInfo si = pm.getServiceInfo(recognizerComponentName, 0);
        return si.loadLabel(pm).toString();
    } catch (PackageManager.NameNotFoundException e) {
        // ignored
    }
    return "[?]";
}
 
Example #25
Source File: ServcesManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean onUnbind(Intent intent) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        Service service = mNameService.get(info.name);
        if (service != null) {
            return handleOnUnbindOne(targetIntent);
        }
    }
    return false;
}
 
Example #26
Source File: ServcesManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int onStart(Context context, Intent intent, int flags, int startId) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo targetInfo = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        if (targetInfo != null) {
            Service service = mNameService.get(targetInfo.name);
            if (service == null) {

                handleCreateServiceOne(context, intent, targetInfo);
            }
            handleOnStartOne(targetIntent, flags, startId);
        }
    }
    return -1;
}
 
Example #27
Source File: PluginManager.java    From Phantom with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel")
private synchronized void removePackage(String packageName) {
    if (TextUtils.isEmpty(packageName)) {
        return;
    }

    final PluginInfo removed = mPackages.remove(packageName);

    if (removed == null) {
        return;
    }

    final ActivityInfo[] activities = removed.packageInfo.activities;
    if (activities != null) {
        for (ActivityInfo activity : activities) {
            mActivities.remove(new ComponentName(activity.packageName, activity.name));
        }
    }

    final ServiceInfo[] services = removed.packageInfo.services;
    if (services != null) {
        for (ServiceInfo service : services) {
            mServices.remove(new ComponentName(service.packageName, service.name));
        }
    }

    PhantomServiceManager.unregisterService(packageName);

    removed.unregisterStaticBroadcastReceiver(mContext);
}
 
Example #28
Source File: AndroidTools.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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;
}
 
Example #29
Source File: VPackageManagerService.java    From container with GNU General Public License v3.0 5 votes vote down vote up
@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;
	}
}
 
Example #30
Source File: HidingManager.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Stops all running services, so nothing can pop up and reveal F-Droid's existence on the system
 */
private static void stopServices(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                PackageManager.GET_SERVICES);
        for (ServiceInfo serviceInfo : packageInfo.services) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(context, serviceInfo.name));
            context.stopService(intent);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}