当前位置:   article > 正文

Android 手动设置系统主Launcher的方法 (需要系统权限)_android 用户不同意也能设置为launcher

android 用户不同意也能设置为launcher
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.PatternMatcher;
import android.util.Log;

import com.teemmo.wifitestdemo.LogUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class LauncherUtil {

    private Intent mIntent;
    private PackageManager packageManager;
    private List<ResolveInfo> mList;
    private static LauncherUtil instance;

    private LauncherUtil() {
    }

    public static LauncherUtil get() {
        if (instance == null) {
            synchronized (LauncherUtil.class) {
                if (instance == null) {
                    instance = new LauncherUtil();
                }
            }
        }

        return instance;
    }

    /****
     * 方法一 只能在没有选择主launcher的时候用
     * @param context
     * @param packageName
     * @param always
     */
    public void startSelected(Activity context, String packageName,boolean always) {
        init(context);

        ResolveInfo ri = null;
        int which = 0;
        for (int i = 0; i < mList.size(); i++) {
            LogUtil.error("Main","recolve:"+mList.get(i).activityInfo.packageName);
            if(mList.get(i).activityInfo.packageName.equals(packageName)){
                ri = mList.get(i);
                break;
            }
        }
        Intent intent = intentForPosition(ri,which);
        onIntentSelected(context,ri, intent, always);
        context.finish();
    }

    /****
     * 方法二 强制设置为主launcher 就算设置了主launcher该方法也能修改
     * @param context
     */
    public void startSelected(Activity context,String packageName) {
        PackageManager packageManager = context.getPackageManager();
        Intent mIntent = new Intent(Intent.ACTION_MAIN, null);
        mIntent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> mList = packageManager
                .queryIntentActivities(mIntent, 0);
        ComponentName[] mHomeComponentSet = new ComponentName[mList.size()];
        ComponentName newHome = null;
        ResolveInfo homeResolve = null;

        for (int i = 0; i < mList.size(); i++) {
            ActivityInfo info = mList.get(i).activityInfo;
            ComponentName activityName = new ComponentName(info.packageName, info.name);
            mHomeComponentSet[i] = activityName;
            if (info.packageName.equals(packageName)) {
                newHome = activityName;
                homeResolve = mList.get(i);
            }
        }

        try {
            if (newHome != null) {
                //设置主launcher
                Class<?>[] types = {IntentFilter.class, Integer.TYPE, ComponentName[].class, ComponentName.class};
                Method replacePreferredActivity = packageManager.getClass().getMethod("replacePreferredActivity", types);
                LogUtil.error("replacePreferredActivity:" + replacePreferredActivity);
                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(Intent.ACTION_MAIN);
                intentFilter.addCategory(Intent.CATEGORY_HOME);
                intentFilter.addCategory(Intent.CATEGORY_DEFAULT);

                replacePreferredActivity.invoke(packageManager, intentFilter, IntentFilter.MATCH_CATEGORY_EMPTY, mHomeComponentSet, newHome);

                //启动应用
                if(homeResolve!=null) {
                    Intent intent = packageManager.getLaunchIntentForPackage(homeResolve.activityInfo.packageName);
                    intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
                            | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
                    ActivityInfo ai = homeResolve.activityInfo;
                    intent.setComponent(new ComponentName(
                            ai.applicationInfo.packageName, ai.name));
                    context.startActivity(intent);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private void init(Context context) {
        packageManager = context.getApplicationContext().getPackageManager();
        mIntent = new Intent(Intent.ACTION_MAIN, null);
        mIntent.addCategory(Intent.CATEGORY_HOME);
        mList = packageManager
                .queryIntentActivities(mIntent, 0);
    }

    private Intent intentForPosition(ResolveInfo ri, int position) {
        DisplayResolveInfo dri = new DisplayResolveInfo(ri, null,
                ri.activityInfo.packageName, packageManager.getLaunchIntentForPackage(ri.activityInfo.packageName));
        LogUtil.error("LauncherUtil:" + dri.origIntent);
        Intent intent = new Intent(dri.origIntent != null
                ? dri.origIntent : mIntent);
        intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
                | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
        ActivityInfo ai = dri.ri.activityInfo;
        intent.setComponent(new ComponentName(
                ai.applicationInfo.packageName, ai.name));
        return intent;
    }

    private void onIntentSelected(Context context, ResolveInfo ri, Intent intent, boolean alwaysCheck) {
        if (alwaysCheck) {
            // Build a reasonable intent filter, based on what matched.
            IntentFilter filter = new IntentFilter();
            if (intent.getAction() != null) {
                filter.addAction(intent.getAction());
            }
            Set<String> categories = intent.getCategories();
            if (categories != null) {
                for (String cat : categories) {
                    filter.addCategory(cat);
                }
            }
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            int cat = ri.match & IntentFilter.MATCH_CATEGORY_MASK;
            Uri data = intent.getData();
            if (cat == IntentFilter.MATCH_CATEGORY_TYPE) {
                String mimeType = intent.resolveType(context);
                if (mimeType != null) {
                    try {
                        filter.addDataType(mimeType);
                    } catch (IntentFilter.MalformedMimeTypeException e) {
                        Log.w("ResolverActivity", e);
                        filter = null;
                    }
                }
            }
            if (data != null && data.getScheme() != null) {
                // We need the data specification if there was no type,
                // OR if the scheme is not one of our magical "file:"
                // or "content:" schemes (see IntentFilter for the reason).
                if (cat != IntentFilter.MATCH_CATEGORY_TYPE
                        || (!"file".equals(data.getScheme())
                        && !"content".equals(data.getScheme()))) {
                    filter.addDataScheme(data.getScheme());
                    // Look through the resolved filter to determine which part
                    // of it matched the original Intent.
                    Iterator<IntentFilter.AuthorityEntry> aIt = ri.filter.authoritiesIterator();
                    if (aIt != null) {
                        while (aIt.hasNext()) {
                            IntentFilter.AuthorityEntry a = aIt.next();
                            if (a.match(data) >= 0) {
                                int port = a.getPort();
                                filter.addDataAuthority(a.getHost(),
                                        port >= 0 ? Integer.toString(port) : null);
                                break;
                            }
                        }
                    }
                    Iterator<PatternMatcher> pIt = ri.filter.pathsIterator();
                    if (pIt != null) {
                        String path = data.getPath();
                        while (path != null && pIt.hasNext()) {
                            PatternMatcher p = pIt.next();
                            if (p.match(path)) {
                                filter.addDataPath(p.getPath(), p.getType());
                                break;
                            }
                        }
                    }
                }
            }
            if (filter != null) {
                final int N = mList.size();
                ComponentName[] set = new ComponentName[N];
                int bestMatch = 0;
                for (int i = 0; i < N; i++) {
                    ResolveInfo r = mList.get(i);
                    set[i] = new ComponentName(r.activityInfo.packageName,
                            r.activityInfo.name);
                    if (r.match > bestMatch) bestMatch = r.match;
                }
                packageManager.addPreferredActivity(filter, bestMatch, set,
                        intent.getComponent());
            }
        }
        if (intent != null) {
            context.startActivity(intent);
        }
    }

    private final class DisplayResolveInfo {
        ResolveInfo ri;
        CharSequence displayLabel;
        Drawable displayIcon;
        CharSequence extendedInfo;
        Intent origIntent;

        DisplayResolveInfo(ResolveInfo pri, CharSequence pLabel,
                           CharSequence pInfo, Intent pOrigIntent) {
            ri = pri;
            displayLabel = pLabel;
            extendedInfo = pInfo;
            origIntent = pOrigIntent;
        }
    }

}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/296494
推荐阅读
相关标签
  

闽ICP备14008679号