下面列出了android.content.Intent#ACTION_MAIN 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private String convertOldValueFormat(String oldValue) {
try {
String[] splitValue = oldValue.split(SEPARATOR);
ComponentName cn = new ComponentName(splitValue[0], splitValue[1]);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(cn);
intent.putExtra("mode", MODE_APP);
String newValue = intent.toUri(0);
setValue(newValue);
Log.d(TAG, "Converted old AppPickerPreference value: " + newValue);
return newValue;
} catch (Exception e) {
Log.e(TAG, "Error converting old AppPickerPreference value: " + e.getMessage());
return null;
}
}
public static List<ResolveInfo> getInstalledPackages(PackageManager pm, Context context) {
DebugLog log = DebugLog.get(context);
if (log.isEnabled()) {
log.writeLog("Getting installed packages. Will try a few different methods to see if I receive a suitable app list.");
}
Intent startupIntent = new Intent(Intent.ACTION_MAIN);
startupIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(startupIntent, 0);
if (log.isEnabled()) {
log.writeLog("Got " + resolveInfos.size() + " apps via queryIntentActivities.");
}
List<ApplicationInfo> appInfos = pm.getInstalledApplications(PackageManager.GET_META_DATA);
if (log.isEnabled()) {
log.writeLog("Got " + appInfos.size() + " apps via getInstalledApplications with GET_META_DATA.");
}
appInfos = pm.getInstalledApplications(0);
if (log.isEnabled()) {
log.writeLog("Got " + appInfos.size() + " apps via getInstalledApplications with no flags");
}
return resolveInfos;
}
public void launch(AppData a) {
//Log.v(APP_TAG, "User launched an app");
if (!DatabaseHelper.hasItem(this, a, CategoryManager.HIDDEN))
addToHistory(a);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setComponent(ComponentName.unflattenFromString(
a.getComponent()));
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
try {
startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Activity is not found", Toast.LENGTH_LONG).show();
DatabaseHelper.removeApp(this, a.getComponent());
loadFilteredApps();
} finally {
if (searchIsOpened) {
closeSearch();
}
}
}
/**
* 为程序创建桌面快捷方式
*
* @param activity Activity
*/
public static void addShortcut(Activity activity) {
Intent shortcut = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 快捷方式的名称
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
activity.getString(R.string.app_name));
shortcut.putExtra("duplicate", false); // 不允许重复创建
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(activity, activity.getClass().getName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// 快捷方式的图标
ShortcutIconResource iconRes = ShortcutIconResource.fromContext(
activity, R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
activity.sendBroadcast(shortcut);
}
private static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
private void focusChromeIfNecessary() {
Set<Integer> visibleTaskIds = getTaskIdsForVisibleActivities();
int tabbedTaskId = -1;
List<WeakReference<Activity>> runningActivities =
ApplicationStatus.getRunningActivities();
for (int i = 0; i < runningActivities.size(); i++) {
Activity activity = runningActivities.get(i).get();
if (activity == null) continue;
if (activity instanceof ChromeTabbedActivity) {
tabbedTaskId = activity.getTaskId();
break;
}
}
// If the task containing the tabbed activity is visible, then do nothing as there is no
// snapshot that would need to be regenerated.
if (visibleTaskIds.contains(tabbedTaskId)) return;
Context context = ContextUtils.getApplicationContext();
Intent startIntent = new Intent(Intent.ACTION_MAIN);
startIntent.setPackage(context.getPackageName());
startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startIntent);
}
/**
* 获取 Launcher activity
* @param packageName 应用包名
* @return package.xx.Activity.className
*/
public static String getLauncherActivity(final String packageName) {
if (packageName == null) return null;
try {
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
List<ResolveInfo> lists = AppUtils.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveinfo : lists) {
if (resolveinfo != null && resolveinfo.activityInfo != null) {
if (resolveinfo.activityInfo.packageName.equals(packageName)) {
return resolveinfo.activityInfo.name;
}
}
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getLauncherActivity");
}
return null;
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
@Override public List<AppsModel> loadInBackground() {
try {
List<AppsModel> entries = new ArrayList<>();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = packageManager.queryIntentActivities(mainIntent, 0);
if (list == null || list.isEmpty()) {
return entries;
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(packageManager));
String appPackage = BuildConfig.APPLICATION_ID;
IconCache iconCache = App.getInstance().getIconCache();
for (ResolveInfo resolveInfo : list) {
if (!resolveInfo.activityInfo.applicationInfo.packageName.equalsIgnoreCase(appPackage)) {
AppsModel model = new AppsModel();
model.setPackageName(resolveInfo.activityInfo.applicationInfo.packageName);
model.setActivityInfoName(resolveInfo.activityInfo.name);
iconCache.getTitleAndIcon(model, resolveInfo, null);
entries.add(model);
}
}
return entries;
} catch (Exception e) {//catching TransactionTooLargeException,
e.printStackTrace();
return AppHelper.getInstalledPackages(getContext());
}
}
/**
* 虚拟home键
*/
public static void virtualHome(Context mContext) {
// 模拟HOME键
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 如果是服务里调用,必须加入new task标识
i.addCategory(Intent.CATEGORY_HOME);
mContext.startActivity(i);
}
/**
* Creates an identical intents and then checks that it is equivalent to an
* Intent generated by {@link org.sana.android.content.Intents#copyOf(Intent) copyOf(Intent)}.
*/
public void testCopyOf() {
// Non-exhaustive list of extras
// We are willing to assume Intent.putExtras(Bundle) works for all if
// it works for two basic extra types
// fake file to check extra parcel
Uri stream = Uri.fromFile(new File("/mnt/sdcard/test.xml"));
// text value to check string extra
String val = "value";
// create an Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_DEFAULT)
.setDataAndType(Subjects.CONTENT_URI, Subjects.CONTENT_TYPE)
.putExtra(Intent.EXTRA_TEXT, val)
.putExtra(Intent.EXTRA_STREAM, stream);
// create a copy using copyOf(Intent)
Intent copyIntent = Intents.copyOf(intent);
// check equality
assertEquals(intent.getAction(), copyIntent.getAction());
assertEquals(intent.getData(), copyIntent.getData());
assertEquals(intent.getType(), copyIntent.getType());
assertEquals(intent.getExtras().getString(Intent.EXTRA_TEXT), copyIntent.getExtras().getString(Intent.EXTRA_TEXT));
assertEquals(intent.getExtras().getParcelable(Intent.EXTRA_STREAM), copyIntent.getExtras().getParcelable(Intent.EXTRA_STREAM));
}
private boolean isCurrentLauncher() {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
final ResolveInfo resolveInfo =
mPm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
return resolveInfo != null &&
mContext.getPackageName().equals(resolveInfo.activityInfo.packageName);
}
@Override
public void handleMessage(Message msg) {
int state = msg.what;
Log.i(TAG, "handleMessage(): " + msg.what);
cancelProgressDialogFragment();
switch (state) {
case SessionService.FAILURE:
loginsRemaining--;
// TODO use a string resource
Toast.makeText(MainActivity.this,
"Username and password incorrect! Logins remaining: "
+ loginsRemaining,
Toast.LENGTH_SHORT).show();
showAuthenticationDialog();
break;
case SessionService.SUCCESS:
loginsRemaining = 0;
Bundle b = msg.getData(); //(Bundle)msg.obj;
Uri uri = Uris.withAppendedUuid(Observers.CONTENT_URI,
b.getString(Intents.EXTRA_OBSERVER));
Log.i(TAG, uri.toString());
onUpdateAppState(b);
Intent data = new Intent();
data.setData(uri);
data.putExtras(b);
onSaveAppState(data);
mIntent = new Intent(Intent.ACTION_MAIN);
break;
default:
Log.e(TAG, "Should never get here");
}
// Finish if remaining logins => 0
if (loginsRemaining == 0) {
finish();
}
}
private XulHttpServerResponse startActivity(XulHttpServerRequest request, String[] params) {
if (params == null) {
return null;
}
String activity = params.length > 0 ? params[0].trim() : null;
String action = params.length > 1 ? params[1].trim() : Intent.ACTION_MAIN;
String category = params.length > 2 ? params[2].trim() : null;
return startActivity(request, activity, action, category);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_APPS + " ( _id INTEGER PRIMARY KEY AUTOINCREMENT," + "packagename TEXT," + "componentname TEXT, " + "weight INTEGER" + ");");
// pre install package
List<AppItem> appList = new ArrayList<AppItem>();
for (String packageName : sAutoAddPackageList) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(packageName);
List<ResolveInfo> ris = mContext.getPackageManager().queryIntentActivities(intent, 0);
if (ris != null && ris.size() > 0) {
for (ResolveInfo ri : ris) {
appList.add(new AppItem(mContext, ri));
}
}
}
for (int i = 0; i < appList.size(); ++i) {
appList.get(i).setIndex(appList.size() - 1 - i);
}
for (AppItem ai : appList) {
ContentValues cv = new ContentValues();
cv.put(AppsColumns.PACKAGE_NAME, ai.getPackageName());
cv.put(AppsColumns.COMPONENT_NAME, ai.getComponentName());
cv.put(AppsColumns.WEIGHT, ai.getIndex());
db.insert(TABLE_APPS, null, cv);
}
}
private void setIcon (boolean enableAltIcon) {
Context ctx = this;
PackageManager pm = getPackageManager();
ActivityManager am = (ActivityManager)getSystemService(Activity.ACTIVITY_SERVICE);
// Enable/disable activity-aliases
pm.setComponentEnabledSetting(
new ComponentName(ctx, "org.witness.informacam.app.InformaActivity-Alt"),
enableAltIcon ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
);
pm.setComponentEnabledSetting(
new ComponentName(ctx, "org.witness.informacam.app.InformaActivity"),
(!enableAltIcon) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
);
// Find launcher and kill it
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
i.addCategory(Intent.CATEGORY_DEFAULT);
List<ResolveInfo> resolves = pm.queryIntentActivities(i, 0);
for (ResolveInfo res : resolves) {
if (res.activityInfo != null) {
am.killBackgroundProcesses(res.activityInfo.packageName);
}
}
// Change ActionBar icon
}
private void loadApps() {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
}
private void loadApps() {
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mApps = getPackageManager().queryIntentActivities(mainIntent, 0);
}
private void startService(Context context) {
Intent serviceIntent = new Intent(Intent.ACTION_MAIN);
serviceIntent.setClass(context, LinphoneService.class);
serviceIntent.putExtra("ForceStartForeground", true);
Compatibility.startService(context, serviceIntent);
}
/**
* Build an Intent to launch a new activity showing the selected fragment.
* The implementation constructs an Intent that re-launches the current activity with the
* appropriate arguments to display the fragment.
*
* @param context The Context.
* @param fragmentName The name of the fragment to display.
* @param args Optional arguments to supply to the fragment.
* @param titleResId Optional title resource id to show for this item.
* @param title Optional title to show for this item.
* @param isShortcut tell if this is a Launcher Shortcut or not
* @return Returns an Intent that can be launched to display the given
* fragment.
*/
public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClass(context, SubSettings.class);
intent.putExtra(EXTRA_SHOW_FRAGMENT, fragmentName);
intent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
intent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE, title);
intent.putExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
return intent;
}