1. 程式人生 > >Android通過包名或類名啟動APP或者一個Activity 以及 判斷APP的執行狀態

Android通過包名或類名啟動APP或者一個Activity 以及 判斷APP的執行狀態

慣例:先上圖後說話,謝謝各位夥伴的支援! 有你們是我的福分!

執行成功效果:          歡迎一起討論和學習,QQ:732258496  微信:15520726587
        

 每日一言:美好的生命應該充滿期待、驚喜和感激!

一、通過包名開啟APP

(1)、第一步:

doStartApplicationWithPackageName("com.grasp.nsuperseller");
(2)、第二步:
/*開啟app*/
@TargetApi(Build.VERSION_CODES.DONUT)
private void doStartApplicationWithPackageName(String packagename) {

    // 
通過包名獲取此APP詳細資訊,包括Activitiesservicesversioncodename等等 PackageInfo packageinfo = null; try { packageinfo = getPackageManager().getPackageInfo(packagename, 0); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (packageinfo == null) { return
; } // 建立一個類別為CATEGORY_LAUNCHER的該包名的Intent Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null); resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER); resolveIntent.setPackage(packageinfo.packageName); // 通過getPackageManager()queryIntentActivities方法遍歷 List<ResolveInfo> resolveinfoList = getPackageManager() .queryIntentActivities(resolveIntent, 0
); ResolveInfo resolveinfo = resolveinfoList.iterator().next(); if (resolveinfo != null) { // packagename = 引數packname String packageName = resolveinfo.activityInfo.packageName; // 這個就是我們要找的該APPLAUNCHERActivity[組織形式:packagename.mainActivityname] String className = resolveinfo.activityInfo.name; // LAUNCHER Intent Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); // 設定ComponentName引數1:packagename引數2:MainActivity路徑 ComponentName cn = new ComponentName(packageName, className); intent.setComponent(cn); startActivity(intent); } }
二、開啟APP中的某個Activity介面

例如:開啟    NSignInHallActivity

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName("com.grasp.nsuperseller", "com.grasp.nsuperseller.activity.signin.NSignInHallActivity");
intent.setComponent(cn);
startActivity(intent);
二、判斷APP的執行狀態

(1)、第一步:

getAppSatus(ClockAlarmActivity.this, "com.grasp.nsuperseller
(2)、第二步:
/**
 * 返回app執行狀態
* 1:程式在前臺執行
* 2:程式在後臺執行
* 3:程式未啟動
* 注意:需要配置許可權<uses-permission android:name="android.permission.GET_TASKS" /> */
public int getAppSatus(Context context, String pageName) {

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(20);

    //判斷程式是否在棧頂
if (list.get(0).topActivity.getPackageName().equals(pageName)) {
        return 1;
    } else {
        //判斷程式是否在棧裡
for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(pageName)) {
                return 2;
            }
        }
        return 3;//棧裡找不到,返回3
}
}