美文网首页
Android 10 设置默认启动桌面

Android 10 设置默认启动桌面

作者: gale_小米 | 来源:发表于2021-11-18 17:23 被阅读0次

1.需求,内置客户应用并且设置系统桌面,并且保留系统launcher
方式1):
1.直接去掉launch的home属性,去掉home属性会有个bug;

对文件进行修改:
/android/frameworks/base/packages/SystemUI/src/com/android/systemui/recents/OverviewProxyService.java

Index: OverviewProxyService.java
===================================================================
--- OverviewProxyService.java   (版本 13296)
+++ OverviewProxyService.java   (版本 13297)
@@ -83,7 +83,11 @@
 
 import javax.inject.Inject;
 import javax.inject.Singleton;
+import android.app.ActivityManager;
+import java.util.List;
 
+
+
 /**
  * Class to send information from overview to launcher with a binder.
  */
@@ -108,7 +112,7 @@
     private final ComponentName mRecentsComponentName;
     private final DeviceProvisionedController mDeviceProvisionedController;
     private final List<OverviewProxyListener> mConnectionCallbacks = new ArrayList<>();
-    private final Intent mQuickStepIntent;
+    private Intent mQuickStepIntent=null;
 
     private Region mActiveNavBarRegion;
 
@@ -466,8 +470,13 @@
         mConnectionBackoffAttempts = 0;
         mRecentsComponentName = ComponentName.unflattenFromString(context.getString(
                 com.android.internal.R.string.config_recentsComponentName));
-        mQuickStepIntent = new Intent(ACTION_QUICKSTEP)
+        
+        if( isRunProcess() ) {
+            mQuickStepIntent = new Intent(ACTION_QUICKSTEP)
                 .setPackage(mRecentsComponentName.getPackageName());
+        }           
+            
+
         mWindowCornerRadius = ScreenDecorationsUtils.getWindowCornerRadius(mContext.getResources());
         mSupportsRoundedCornersOnWindows = ScreenDecorationsUtils
                 .supportsRoundedCornersOnWindows(mContext.getResources());
@@ -494,6 +503,24 @@
         statusBarWinController.registerCallback(mStatusBarWindowCallback);
     }
 
+    
+    
+    //判断是否在主进程,这个方法判断进程名或者pid都可以,如果进程名一样那pid肯定也一样
+    public boolean isRunProcess() {
+        ActivityManager am = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE));
+        List<ActivityManager.RunningAppProcessInfo> infos = am.getRunningAppProcesses();
+        String mainProcessName ="com.android.launcher3";//getPackageName();
+        //int myPid = android.os.Process.myPid();
+        //info.pid == myPid &&
+        for (ActivityManager.RunningAppProcessInfo info : infos) {
+            if ( mainProcessName.equals(info.processName)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+
     public void notifyBackAction(boolean completed, int downX, int downY, boolean isButton,
             boolean gestureSwipeLeft) {
         try {
@@ -753,9 +780,11 @@
     }
 
     private void updateEnabledState() {
-        mIsEnabled = mContext.getPackageManager().resolveServiceAsUser(mQuickStepIntent,
-                MATCH_SYSTEM_ONLY,
-                ActivityManagerWrapper.getInstance().getCurrentUserId()) != null;
+        if(mQuickStepIntent!=null){
+            mIsEnabled = mContext.getPackageManager().resolveServiceAsUser(mQuickStepIntent,
+                    MATCH_SYSTEM_ONLY,
+                    ActivityManagerWrapper.getInstance().getCurrentUserId()) != null;
+        }
     }
 
     @Override
@@ -772,7 +801,9 @@
                 .isCurrentUserSetup());
         pw.print("  connectionBackoffAttempts="); pw.println(mConnectionBackoffAttempts);
 
-        pw.print("  quickStepIntent="); pw.println(mQuickStepIntent);
+        if( mQuickStepIntent !=null ){
+            pw.print("  quickStepIntent="); pw.println(mQuickStepIntent);
+        }
         pw.print("  quickStepIntentResolved="); pw.println(isEnabled());
         pw.print("  mSysUiStateFlags="); pw.println(mSysUiStateFlags);
         pw.println("    " + QuickStepContract.getSystemUiStateString(mSysUiStateFlags));

方式2:直接设置为默认桌面
参考:https://blog.csdn.net/qq_27256793/article/details/105413675
在全志10上面,这个方法不行,所以做了些修改
/android/frameworks/base/core/java/com/android/internal/app/ResolverActivity.java

Index: ResolverActivity.java
===================================================================
@@ -287,6 +287,19 @@
                 supportsAlwaysUseOption);
     }
 
+    private boolean setupDefaultLauncher(String packageName) {
+        DisplayResolveInfo info = mAdapter.getDefaultHome(packageName);
+        if (info == null) {
+            Log.w(TAG, "not find default Home");
+            return false;
+        }
+        onTargetSelected(info, true);
+        MetricsLogger.action(this, MetricsProto.MetricsEvent.ACTION_APP_DISAMBIG_ALWAYS);
+        dismiss();
+        return true;
+    }
+
     protected void onCreate(Bundle savedInstanceState, Intent intent,
             CharSequence title, int defaultTitleRes, Intent[] initialIntents,
             List<ResolveInfo> rList, boolean supportsAlwaysUseOption) {
@@ -334,6 +347,16 @@
             return;
         }
 
+        //add start
+        boolean isSetDefLauncher= (Settings.System.getInt(getContentResolver(), "xxx", 0)  == 0);
+        if(isSetDefLauncher){
+            if(setupDefaultLauncher("xxx")){
+                Settings.System.putInt(getContentResolver(), "xxx", 1);
+                finish();
+                return;
+            }
+        }
+
         final ResolverDrawerLayout rdl = findViewById(R.id.contentPanel);
         if (rdl != null) {
             rdl.setOnDismissedListener(new ResolverDrawerLayout.OnDismissedListener() {
@@ -1632,6 +1655,29 @@
             mResolverListController = resolverListController;
         }
 
+        public DisplayResolveInfo getDefaultHome(String packageName){
+            DisplayResolveInfo otherProfile=null;
+            for (int i = 0; i < mUnfilteredResolveList.size(); i++) {
+                ResolvedComponentInfo info = mUnfilteredResolveList.get(i);
+                for (int j = 0; j < info.getCount(); j++) {
+                    ResolveInfo _info = info.getResolveInfoAt(j);
+                    Log.w(TAG, "info.activityInfo.packageName ="+_info.activityInfo.packageName);
+                    if (_info.activityInfo.packageName.equals(packageName)) {
+                         otherProfile = new DisplayResolveInfo(info.getIntentAt(j),
+                            info.getResolveInfoAt(j),
+                            info.getResolveInfoAt(j).loadLabel(mPm),
+                            info.getResolveInfoAt(j).loadLabel(mPm),
+                            getReplacementIntent(info.getResolveInfoAt(j).activityInfo,
+                                    info.getIntentAt(j)));
+                        return otherProfile;
+                    }
+                }
+            }
+            return otherProfile;
+        }
+
         public void handlePackagesChanged() {
             rebuildList();
             if (getCount() == 0) {

方式3:

/android/packages/apps/Provision/src/com/android/provision/DefaultActivity.java
===================================================================
@@ -22,6 +22,18 @@
 import android.os.Bundle;
 import android.provider.Settings;
 
+import android.app.AppOpsManager;
+import android.content.ComponentName;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PermissionInfo;
+import android.content.pm.ResolveInfo;
+import java.util.ArrayList;
+import java.util.List;
+import android.content.Context;
+
 /**
  * Application that sets the provisioned bit, like SetupWizard does.
  */
@@ -40,9 +52,112 @@
         ComponentName name = new ComponentName(this, DefaultActivity.class);
         pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                 PackageManager.DONT_KILL_APP);
-
+        setAppPermission("xxx"); 
+        setHomeDefault("xxx", "xxx");
         // terminate the activity.
         finish();
     }
+
+
+    public void setAppPermission(String pkgName) {
+        PackageManager pm = getApplicationContext().getPackageManager();
+        AppOpsManager  mAppOps = (AppOpsManager) getApplicationContext().getSystemService(Context.APP_OPS_SERVICE);
+        try {
+            PackageInfo pkgInfo = pm.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);
+            String sharedPkgList[] = pkgInfo.requestedPermissions;
+            for (int i = 0; i < sharedPkgList.length; i++) {
+                String permName = sharedPkgList[i];
+                PermissionInfo permissionInfo;
+                try {
+                    permissionInfo = pm.getPermissionInfo(permName, 0);
+                } catch (PackageManager.NameNotFoundException e) {
+                    continue;
+                }
+                final int opCode = AppOpsManager.permissionToOpCode(permName);
+                boolean hasAopsCode = opCode > AppOpsManager.OP_NONE && opCode < AppOpsManager._NUM_OP;
+                String aopStr = AppOpsManager.permissionToOp(permName);
+                boolean hasAopsOp = aopStr != null;
+                boolean onlyAops = false;
+                final boolean granted = (pkgInfo.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0;
+                if ((permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) != PermissionInfo.PROTECTION_DANGEROUS || (permissionInfo.flags & PermissionInfo.FLAG_INSTALLED) == 0 || (permissionInfo.flags & PermissionInfo.FLAG_REMOVED) != 0) {
+                    if (permName.startsWith("android.") && (hasAopsCode || hasAopsOp)) {
+                        onlyAops = true;
+                        android.util.Log.d("SHENJU", "permissionName=" + permName + ",opCode=" + opCode);
+                    } else continue;
+                }
+                boolean isAopsAllowed = mAppOps.checkOpNoThrow(opCode, pkgInfo.applicationInfo.uid, pkgInfo.packageName) == AppOpsManager.MODE_ALLOWED;
+                if ((hasAopsCode || onlyAops) && !isAopsAllowed)
+                    mAppOps.setMode(opCode, pkgInfo.applicationInfo.uid, pkgInfo.packageName, AppOpsManager.MODE_ALLOWED);
+                if ((hasAopsOp || onlyAops) && !isAopsAllowed)
+                    mAppOps.setUidMode(aopStr, pkgInfo.applicationInfo.uid, AppOpsManager.MODE_ALLOWED);
+                if (!granted && !onlyAops) {
+                    pm.grantRuntimePermission(pkgName, permName, android.os.Process.myUserHandle());
+                }
+                // set flags
+                pm.updatePermissionFlags(permName, pkgName, PackageManager.FLAG_PERMISSION_USER_FIXED | PackageManager.FLAG_PERMISSION_USER_SET | PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, android.os.Process.myUserHandle());
+            }
+            List<AppOpsManager.PackageOps> ops = mAppOps.getOpsForPackage(pkgInfo.applicationInfo.uid, pkgName, null,null);
+            if (ops == null || ops.size() == 0) return;
+            for (AppOpsManager.PackageOps packageOps : ops) {
+                List<AppOpsManager.OpEntry> entries = packageOps.getOps();
+                if (entries == null || entries.size() == 0) continue;
+                for (AppOpsManager.OpEntry opEntry : entries) {
+                    mAppOps.setMode(opEntry.getOp(), packageOps.getUid(), pkgName, AppOpsManager.MODE_ALLOWED);
+                }
+            }
+        } catch (Exception e) {
+            android.util.Log.e("SHENJU", "++setAppPermission exception ,the packageName is " + pkgName, e);
+        }
+    }
+
+    public void setHomeDefault(String defaultlauncherpckname, String defaultlauncherclsname) {
+        final PackageManager mPm = getApplicationContext().getPackageManager();
+        // 判断指定的 launcher 是否存在
+        if (hasApkInstalled(defaultlauncherpckname)) {
+            // 清除当前默认 launcher
+            ArrayList<IntentFilter> intentList = new ArrayList<IntentFilter>();
+            ArrayList<ComponentName> cnList = new ArrayList<ComponentName>();
+            mPm.getPreferredActivities(intentList, cnList, null);
+            IntentFilter dhIF = null;
+            for (int i = 0; i < cnList.size(); i++) {
+                dhIF = intentList.get(i);
+                if (dhIF.hasAction(Intent.ACTION_MAIN) && dhIF.hasCategory(Intent.CATEGORY_HOME)) {
+                    mPm.clearPackagePreferredActivities(cnList.get(i).getPackageName());
+                }
+            }
+            // 获取所有 launcher activity
+            Intent intent = new Intent(Intent.ACTION_MAIN);
+            intent.addCategory(Intent.CATEGORY_HOME);
+            List<ResolveInfo> list = new ArrayList<ResolveInfo>();
+            list = mPm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
+            // get all components and the best match 
+            IntentFilter filter = new IntentFilter();
+            filter.addAction(Intent.ACTION_MAIN);
+            filter.addCategory(Intent.CATEGORY_HOME);
+            filter.addCategory(Intent.CATEGORY_DEFAULT);
+            final int N = list.size();
+            // 设置默认 launcher
+            ComponentName launcher = new ComponentName(defaultlauncherpckname, defaultlauncherclsname);
+            ComponentName[] set = new ComponentName[N];
+            int defaultMatch = 0;
+            for (int i = 0; i < N; i++) {
+                ResolveInfo r = list.get(i);
+                set[i] = new ComponentName(r.activityInfo.packageName, r.activityInfo.name);
+                if (launcher.getClassName().equals(r.activityInfo.name)) {
+                    defaultMatch = r.match;
+                }
+            }
+            mPm.addPreferredActivity(filter, defaultMatch, set, launcher);
+        }
+    }
+
+    private boolean hasApkInstalled(String pkgname) {
+        try {
+            getApplicationContext().getPackageManager().getPackageInfo(pkgname, 0);
+        } catch (Exception e) {
+            return false;
+        }
+        return true;
+    }
 }

相关文章

网友评论

      本文标题:Android 10 设置默认启动桌面

      本文链接:https://www.haomeiwen.com/subject/qkfjtrtx.html