根据app的名字启动第三方app

如果已知第三方app的名字,也就是label,想在自己的项目启动该app,代码如下:

package com.aiiage.aiiagerobot.helpers;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2016/8/24.
 * 根据app的名字调用第三方app,不需要知道包名和类名
 */
public class startOtherAppHelper {
    private static PackageManager mPackageManager;
    private static List<ResolveInfo> mAllApps;
    private static Context mContext;
    public static boolean openApp(Context context, String appName) {
        mContext = context;
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mPackageManager = mContext.getPackageManager();
        mAllApps = mPackageManager.queryIntentActivities(mainIntent, 0);
        //按报名排序
        Collections.sort(mAllApps, new ResolveInfo.DisplayNameComparator(mPackageManager));
        for (ResolveInfo res : mAllApps) {
            //该应用的label名
            String label = res.loadLabel(mPackageManager).toString();
            if (appName.equals(label)) {//如果存在该名字,启动app
                String pkg = res.activityInfo.packageName;
                String cls = res.activityInfo.name;
                ComponentName componet = new ComponentName(pkg, cls);
                Intent intent = new Intent();
                intent.setComponent(componet);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
                return true;
            }
        }
        return false;
    }
}
然后在调用的地方直接用就行了,假如我想调用百度地图,直接

startOtherAppHelper.openApp(mContext,"百度地图");
就可以了



猜你喜欢

转载自blog.csdn.net/meak_962/article/details/52304181