判断系统是否安装某APP - 以高德地图为例

前言

近日在整合系统项目的时候有个小功能,就是跳转到百度地图或者高德地图。这块以后应该会有不少用到的地方,于是自己做了一些整理。闲话不说直接上代码。

代码

因为只是一个小功能,所以代码量很少。

工具类文件


public class SystemUtils {

    private static SystemUtils systemUtils;

    public static SystemUtils getInstance() {
        if (systemUtils != null) {
            return systemUtils;
        } else {
            return new SystemUtils();
        }
    }

    /**
     * 判断系统是否安装某app
     *
     * @param packageName 包名
     * @return
     */
    public boolean appIsInstalled(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        List packageInfoList = manager.getInstalledPackages(0);
        if (packageInfoList != null) {
            for (int i = 0; i < packageInfoList.size(); i++) {
                String package_name = packageInfoList.get(i).packageName;
                if (package_name.equals(packageName)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取某app的信息
     *
     * @param packageName 包名
     * @return
     */
    public PackageInfo getAppInfo(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        List packageInfoList = manager.getInstalledPackages(0);
        if (packageInfoList != null) {
            for (int i = 0; i < packageInfoList.size(); i++) {
                String package_name = packageInfoList.get(i).packageName;
                if (package_name.equals(packageName)) {
                    return packageInfoList.get(i);
                }
            }
        }
        return null;
    }
}

主页调用


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btnMain;
    private TextView tvMain;
    private SystemUtils systemUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        btnMain = (Button) findViewById(R.id.btn_main);
        tvMain = (TextView) findViewById(R.id.tv_main);
        btnMain.setOnClickListener(this);
        systemUtils = SystemUtils.getInstance();
    }

    @Override
    public void onClick(View v) {
        if (systemUtils.appIsInstalled(this, "com.autonavi.minimap")) {
            PackageInfo packageInfo = systemUtils.getAppInfo(this, "com.autonavi.minimap");
            tvMain.setText(packageInfo.packageName
                    + "\r\n" + packageInfo.versionName
                    + "\r\n" + packageInfo.applicationInfo
            );
        } else {
            Toast.makeText(this, "暂未安装高德地图", Toast.LENGTH_SHORT).show();
        }
    }
}

你可能感兴趣的:(基础文章)