下面列出了android.content.ComponentName#getPackageName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public boolean appHasCustomLabel(ComponentName appname) {
String actvname = appname.getClassName();
String pkgname = appname.getPackageName();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(APP_TABLE, new String [] {CUSTOMLABEL}, ACTVNAME + "=? and " + PKGNAME + "=?", new String[]{actvname, pkgname}, null, null, null);
try {
if (cursor.moveToNext()) { //ACTVNAME, PKGNAME, LABEL, CATID
String customlabel = cursor.getString(cursor.getColumnIndex(CUSTOMLABEL));
if (customlabel!=null && !customlabel.isEmpty()) {
return true;
}
}
} finally {
cursor.close();
}
return false;
}
public void deleteApp(ComponentName appname) {
String actvname = appname.getClassName();
String pkgname = appname.getPackageName();
try {
AppLauncher app = getApp(appname);
if (app != null && (app.isLink() || app.isWidget())) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(APP_TABLE, ACTVNAME + "=? and " + PKGNAME + "=?", new String[]{actvname, pkgname});
AppLauncher.removeAppLauncher(actvname,pkgname);
return;
}
} catch (Exception e) {
Log.e("LaunchDB", "Can't delete app " + actvname, e);
}
deleteApp(actvname, pkgname);
}
private boolean extractCallerAuthDomain() {
ComponentName callingActivity = getCallingActivity();
if (callingActivity == null) {
Log.w(LOG_TAG, "No calling activity found for save call");
return false;
}
String callingPackage = callingActivity.getPackageName();
AuthenticationDomain authDomain =
AuthenticationDomain.fromPackageName(this, callingPackage);
if (null == authDomain) {
return false;
}
mCallerAuthDomain = authDomain;
return true;
}
private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
final int uid) {
String packageName = null;
if (componentName != null) {
// If they gave us a component name verify they own the
// package
packageName = componentName.getPackageName();
enforcePackageName(packageName, uid);
}
// Check that they can make calls on behalf of the user and
// get the final user id
int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
true /* allowAll */, true /* requireFull */, "getSessions", packageName);
// Check if they have the permissions or their component is
// enabled for the user they're calling from.
enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
return resolvedUserId;
}
/**
* Used by: plugin EditActivity.
*
* Description as above.
*
* This version also includes backwards compatibility with pre 4.2 Tasker versions.
* At some point this function will be deprecated.
*
* @param editActivity the plugin edit activity, needed to test calling Tasker version
* @see #setVariableReplaceKeys(Bundle, String[])
*/
public static boolean hostSupportsOnFireVariableReplacement( Activity editActivity ) {
boolean supportedFlag = hostSupportsOnFireVariableReplacement( editActivity.getIntent().getExtras() );
if ( ! supportedFlag ) {
ComponentName callingActivity = editActivity.getCallingActivity();
if ( callingActivity == null )
Log.w( TAG, "hostSupportsOnFireVariableReplacement: null callingActivity, defaulting to false" );
else {
String callerPackage = callingActivity.getPackageName();
// Tasker only supporteed this from 1.0.10
supportedFlag =
( callerPackage.startsWith( BASE_KEY ) ) &&
( getPackageVersionCode( editActivity.getPackageManager(), callerPackage ) > FIRST_ON_FIRE_VARIABLES_TASKER_VERSION )
;
}
}
return supportedFlag;
}
@Override
public int schedule(JobInfo job) throws RemoteException {
int vuid = VBinder.getCallingUid();
int id = job.getId();
ComponentName service = job.getService();
JobId jobId = new JobId(vuid, service.getPackageName(), id);
JobConfig config = mJobStore.get(jobId);
if (config == null) {
config = new JobConfig(mGlobalJobId++, service.getClassName(), job.getExtras());
mJobStore.put(jobId, config);
} else {
config.serviceName = service.getClassName();
config.extras = job.getExtras();
}
saveJobs();
mirror.android.app.job.JobInfo.jobId.set(job, config.virtualJobId);
mirror.android.app.job.JobInfo.service.set(job, mJobProxyComponent);
return mScheduler.schedule(job);
}
private static int getProcessByComponentName(ComponentName cn) {
if (cn == null) {
// 如果Intent里面没有带ComponentName,则我们不支持此特性,直接返回null
// 外界会直接调用其系统的对应方法
return PROCESS_UNKNOWN;
}
String pn = cn.getPackageName();
// 开始尝试获取插件的ServiceInfo
ComponentList col = PluginFactory.queryPluginComponentList(pn);
if (col == null) {
if (LogDebug.LOG) {
Log.e(TAG, "getProcessByComponentName(): Fetch Component List Error! pn=" + pn);
}
return PROCESS_UNKNOWN;
}
ServiceInfo si = col.getService(cn.getClassName());
if (si == null) {
if (LogDebug.LOG) {
Log.e(TAG, "getProcessByComponentName(): Not register! pn=" + pn);
}
return PROCESS_UNKNOWN;
}
int p = PluginClientHelper.getProcessInt(si.processName);
if (LogDebug.LOG) {
Log.d(TAG, "getProcessByComponentName(): Okay! Process=" + p + "; pn=" + pn);
}
return p;
}
/**
* 开启一个插件的Activity <p>
* 其中Intent的ComponentName的Key应为插件名(而不是包名),可使用createIntent方法来创建Intent对象
*
* @param context Context对象
* @param intent 要打开Activity的Intent,其中ComponentName的Key必须为插件名
* @return 插件Activity是否被成功打开?
* FIXME 是否需要Exception来做?
* @see #createIntent(String, String)
* @since 1.0.0
*/
public static boolean startActivity(Context context, Intent intent) {
// TODO 先用旧的开启Activity方案,以后再优化
ComponentName cn = intent.getComponent();
if (cn == null) {
// TODO 需要支持Action方案
return false;
}
String plugin = cn.getPackageName();
String cls = cn.getClassName();
return PluginFactory.startActivityWithNoInjectCN(context, intent, plugin, cls, IPluginManager.PROCESS_AUTO);
}
public static ComponentName getComponentName(Context context, Intent intent) {
PackageManager packageManager = context.getPackageManager();
ComponentName resolvedComponentName = intent.resolveActivity(packageManager);
try {
ActivityInfo activityInfo = packageManager.getActivityInfo(resolvedComponentName, 0);
if (activityInfo.targetActivity != null) {
return new ComponentName(resolvedComponentName.getPackageName(), activityInfo.targetActivity);
}
} catch (PackageManager.NameNotFoundException e) {
// TODO nothing
}
return resolvedComponentName;
}
public static ComponentName getComponentName(Context context, Intent intent) {
PackageManager packageManager = context.getPackageManager();
ComponentName resolvedComponentName = intent.resolveActivity(packageManager);
try {
ActivityInfo activityInfo = packageManager.getActivityInfo(resolvedComponentName, 0);
if (activityInfo.targetActivity != null) {
return new ComponentName(resolvedComponentName.getPackageName(), activityInfo.targetActivity);
}
} catch (PackageManager.NameNotFoundException e) {
// TODO nothing
}
return resolvedComponentName;
}
private void initializeCallingPackage(final Activity activity) {
ComponentName componentName = activity.getCallingActivity();
if (componentName == null) {
return;
}
callingPackage = componentName.getPackageName();
}
/**
* 判断指定的应用是否在前台运行
*
* @param packageName
* @return
*/
private boolean isAppForeground(String packageName)
{
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
String currentPackageName = cn.getPackageName();
return !TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(packageName);
}
/**
* getServiceInfo
*
* @param component ComponentName
* @param flags flags
* @param userId userId
* @return ServiceInfo
*/
public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
String packageName = component.getPackageName();
ServiceInfo result = null;
if (isPlugin(packageName)) {
PackageInfo pkgInfo = getPluginPackageInfo(packageName);
if (pkgInfo == null) {
return null;
}
for (int i = 0; i < pkgInfo.services.length; i++) {
if (component.getClassName().equalsIgnoreCase(pkgInfo.services[i].name)) {
result = pkgInfo.services[i];
break;
}
}
} else {
if (userId == INVALID_USER_ID) {
result = mTarget.getServiceInfo(component, flags);
} else {
result = mTarget.getServiceInfo(component, flags, userId);
}
}
return result;
}
/**
* Obtain an {@link Intent} that will launch an explicit target activity
* specified by sourceActivityClass's {@link #PARENT_ACTIVITY} <meta-data>
* element in the application's manifest.
*
* @param context Context for looking up the activity component for the source activity
* @param componentName ComponentName for the source Activity
* @return a new Intent targeting the defined parent activity of sourceActivity
* @throws NameNotFoundException if the ComponentName for sourceActivityClass is invalid
*/
public static Intent getParentActivityIntent(Context context, ComponentName componentName)
throws NameNotFoundException {
String parentActivity = getParentActivityName(context, componentName);
if (parentActivity == null) return null;
// If the parent itself has no parent, generate a main activity intent.
final ComponentName target = new ComponentName(
componentName.getPackageName(), parentActivity);
final String grandparent = getParentActivityName(context, target);
final Intent parentIntent = grandparent == null
? IntentCompat.makeMainActivity(target)
: new Intent().setComponent(target);
return parentIntent;
}
/**
* Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
* provided by the same package which is set to be global search activity.
* If widgetCategory is not supported, or no such widget is found, returns the first widget
* provided by the package.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
SearchManager searchManager =
(SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
ComponentName searchComponent = searchManager.getGlobalSearchActivity();
if (searchComponent == null) return null;
String providerPkg = searchComponent.getPackageName();
AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
if (info.provider.getPackageName().equals(providerPkg)) {
if (ATLEAST_JB_MR1) {
if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
return info;
} else if (defaultWidgetForSearchPackage == null) {
defaultWidgetForSearchPackage = info;
}
} else {
return info;
}
}
}
return defaultWidgetForSearchPackage;
}
/** Returns Package name of base activity.<p>
* Requires GET_TASK permission
* @param context Context to get base activity information
* @return String containing base package name
*/
public static String getBaseActivityPackageName(Context context) {
ComponentName activity = getBaseActivity(context);
if (activity == null) {
return null;
}
return activity.getPackageName();
}
public ThirdPartyWallpaperPickerListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mPackageManager = context.getPackageManager();
mIconSize = context.getResources().getDimensionPixelSize(R.dimen.wallpaperItemIconSize);
final PackageManager pm = mPackageManager;
final Intent pickWallpaperIntent = new Intent(Intent.ACTION_SET_WALLPAPER);
final List<ResolveInfo> apps =
pm.queryIntentActivities(pickWallpaperIntent, 0);
// Get list of image picker intents
Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickImageIntent.setType("image/*");
final List<ResolveInfo> imagePickerActivities =
pm.queryIntentActivities(pickImageIntent, 0);
final ComponentName[] imageActivities = new ComponentName[imagePickerActivities.size()];
for (int i = 0; i < imagePickerActivities.size(); i++) {
ActivityInfo activityInfo = imagePickerActivities.get(i).activityInfo;
imageActivities[i] = new ComponentName(activityInfo.packageName, activityInfo.name);
}
outerLoop:
for (ResolveInfo info : apps) {
final ComponentName itemComponentName =
new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
final String itemPackageName = itemComponentName.getPackageName();
// Exclude anything from our own package, and the old Launcher,
// and live wallpaper picker
if (itemPackageName.equals(context.getPackageName()) ||
itemPackageName.equals("com.android.launcher") ||
itemPackageName.equals("com.android.wallpaper.livepicker")) {
continue;
}
// Exclude any package that already responds to the image picker intent
for (ResolveInfo imagePickerActivityInfo : imagePickerActivities) {
if (itemPackageName.equals(
imagePickerActivityInfo.activityInfo.packageName)) {
continue outerLoop;
}
}
mThirdPartyWallpaperPickers.add(new ThirdPartyWallpaperTile(info));
}
}
private ServiceRecord retrieveServiceLocked(Intent service) {
ComponentName cn = service.getComponent();
ServiceRecord sr = mServicesByName.get(cn);
if (sr != null) {
return sr;
}
sr = mServicesByIntent.get(service);
if (sr != null) {
return sr;
}
String pn = cn.getPackageName();
String name = cn.getClassName();
// 看这个Plugin是否可以被打开
if (!RePlugin.isPluginInstalled(pn)) {
if (LOGR) {
LogRelease.e(PLUGIN_TAG, "psm.is: p n ex " + name);
}
return null;
}
// 开始尝试获取插件的ServiceInfo
ComponentList col = PluginFactory.queryPluginComponentList(pn);
if (col == null) {
if (LOG) {
Log.e(TAG, "installServiceLocked(): Fetch Component List Error! pn=" + pn);
}
return null;
}
ServiceInfo si = col.getService(cn.getClassName());
if (si == null) {
if (LOG) {
Log.e(TAG, "installServiceLocked(): Not register! pn=" + pn);
}
return null;
}
// 构建,放入表中
Intent.FilterComparison fi = new Intent.FilterComparison(service);
sr = new ServiceRecord(cn, fi, si);
mServicesByName.put(cn, sr);
mServicesByIntent.put(fi, sr);
return sr;
}
/**
* Get the package name of the {@link Activity} that sent the
* {@link Intent} that started this {@code Activity}.
* <p/>
* <strong>WARNING</strong>: If the {@code Activity} has
* {@code android:launchMode="singleInstance"} or {@code "singleTask"}, then
* this method will not disconnect because it is not possible to get the
* calling {@code Activity}, as set by
* {@link Activity#startActivityForResult(Intent, int)}
*
* @param activity the {@code Activity} to check for the {@code Intent}
* @return the package of the sending app or {@code null} if it was not a
* {@code ACTION_CONNECT Intent} or the {@code Intent} was not sent
* with {@link Activity#startActivityForResult(Intent, int)}
*/
public static String getCallingPackageName(Activity activity) {
// getCallingPackage() was unstable until android-18, use this
ComponentName componentName = activity.getCallingActivity();
if (componentName == null)
return null;
String packageName = componentName.getPackageName();
if (TextUtils.isEmpty(packageName)) {
Log.e(activity.getClass().getSimpleName(),
"Received Intent without sender! The Intent must be sent using startActivityForResult() and received without launchMode singleTask or singleInstance!");
}
return packageName;
}
private static String makeSafeName(ComponentName cname, IconType iconType) {
String name = cname.getPackageName() + ":" + cname.getClassName();
String fname = makeSafeName(name);
if (iconType!=null) fname += "." + iconType.name();
fname += ".png";
return fname;
}