1. 程式人生 > >Android開發中跳到第三方App的方法

Android開發中跳到第三方App的方法

Android開發中,有時候會用到從一個Activity跳轉到別的App中,方法如下

 private PackageManager mPackageManager;
 private List<ResolveInfo> mAllApps;

  /**
     * 檢查系統應用程式,並開啟
     */
    private void openApp(){
        //應用過濾條件
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mPackageManager = context.getPackageManager();
        mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
        //按包名排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));

        for(ResolveInfo res : mAllApps){
            //該應用的包名和主Activity
            String pkg = res.activityInfo.packageName;
            String cls = res.activityInfo.name;

            if(pkg.contains("要跳轉App的包名")){
                ComponentName componet = new ComponentName(pkg, cls);
               
                Intent intent = new Intent();
                intent.setComponent(componet);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }else{
            	Toast.makeText(context, "您未能成功開啟XXX,請下載或手動進入XXX進行業務操作",2000).show();
            }
        }
    }
在Activity中直接呼叫openApp方法即可,也可以不用判斷使用者是否安裝了要跳轉的App,直接這樣寫
ComponentName componet = new ComponentName("要跳轉的包名", "<span style="font-family: Arial, Helvetica, sans-serif;">要跳轉的</span><span style="font-family: Arial, Helvetica, sans-serif;">類名");</span>
Intent intent = new Intent();
intent.setComponent(componet);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
當然這樣寫使用者體驗是不好的,不建議