zoukankan      html  css  js  c++  java
  • 一般Activity 切换到后台

    @Override
        public void onBackPressed() {
            ResolveInfo launcherResolve=queryCurrentLauncher();
            Intent intent=new Intent();
            intent.addCategory(Intent.ACTION_MAIN);
            ComponentName componentName=new ComponentName(launcherResolve.activityInfo.packageName,launcherResolve.activityInfo.name);
            intent.setComponent(componentName);
            startActivitySafely(intent);
        }
        private void startActivitySafely(Intent intent){
            try{
                startActivity(intent);
                Toast.makeText(this, "切换到后台成功", Toast.LENGTH_SHORT).show();
            }catch (Exception e){
                Toast.makeText(this, "切换到后台失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    
        private ResolveInfo queryCurrentLauncher() {
            Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
            launcherIntent.addCategory(Intent.CATEGORY_HOME);
            launcherIntent.addCategory(Intent.CATEGORY_DEFAULT);
            List<ResolveInfo> launcherInfoList = getPackageManager().queryIntentActivities(launcherIntent, PackageManager.MATCH_DEFAULT_ONLY);
    
            ResolveInfo launcherResolveInfo = null;
            ActivityManager activityManager = (ActivityManager) getSystemService(Service.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(30);
            Iterator<ActivityManager.RunningTaskInfo> itInfo = tasks.iterator();
            while (itInfo.hasNext()) {
                ActivityManager.RunningTaskInfo info = itInfo.next();
                for (ResolveInfo resolveInfo : launcherInfoList) {
                    String name1 = info.topActivity.getClassName();
                    String namme2 = resolveInfo.activityInfo.name;
                    if (name1.equals(namme2)) {
                        //获取当前使用的桌面
                        launcherResolveInfo = resolveInfo;
                        return launcherResolveInfo;
                    }
                }
            }
            return launcherResolveInfo;
        }
  • 相关阅读:
    HTTP的GET和POST请求
    移动开发平台性能比較
    Struts2之类型转换器的使用
    对Socket CAN的理解(4)——【Socket CAN接收数据流程】
    当罗密欧遇到朱丽叶... ...当指针遇到数组
    Qt的Script、Quick、QML的关系与总结
    nyoj27水池数目 (DFS)
    HBase行锁原理及实现
    poj1852ant
    JSTL&EL表达式
  • 原文地址:https://www.cnblogs.com/xushihai/p/4818397.html
Copyright © 2011-2022 走看看