包含的功能有:

获取系统中所有APP应用、获取用户安装的APP应用、根据包名和Activity启动类查询应用信息、跳转到WIFI设置、WIFI网络开关、移动网络开关、GPS开关 当前若关则打开 当前若开则关闭、调节系统音量、设置亮度、获取屏幕的亮度、跳转到系统设置、获取文件夹下所有文件、获取视频的缩略图 、打开视频文件...
工具类会持续更新,与大家共同学习进步。

SystemUtils.java

package com.player.utils;
 
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.provider.Settings;
 
import com.player.bean.AppInfo;
 
public class SystemUtils {
 
    /**
     * 获取系统所有APP应用
     *
     * @param context
     */
    public static ArrayList getAllApp(Context context) {
        PackageManager manager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<resolveinfo> apps = manager.queryIntentActivities(mainIntent, 0);
        // 将获取到的APP的信息按名字进行排序
        Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
        ArrayList appList = new ArrayList();
        for (ResolveInfo info : apps) {
            AppInfo appInfo = new AppInfo();
 
            appInfo.setAppLable(info.loadLabel(manager) + "");
            appInfo.setAppIcon(info.loadIcon(manager));
            appInfo.setAppPackage(info.activityInfo.packageName);
            appInfo.setAppClass(info.activityInfo.name);
            appList.add(appInfo);
            System.out.println("info.activityInfo.packageName="+info.activityInfo.packageName);
            System.out.println("info.activityInfo.name="+info.activityInfo.name);
        }
 
        return appList;
    }
 
    /**
     * 获取用户安装的APP应用
     *
     * @param context
     */
    public static ArrayList getUserApp(Context context) {
        PackageManager manager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<resolveinfo> apps = manager.queryIntentActivities(mainIntent, 0);
        // 将获取到的APP的信息按名字进行排序
        Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
        ArrayList appList = new ArrayList();
        for (ResolveInfo info : apps) {
            AppInfo appInfo = new AppInfo();
            ApplicationInfo ainfo = info.activityInfo.applicationInfo;
            if ((ainfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                appInfo.setAppLable(info.loadLabel(manager) + "");
                appInfo.setAppIcon(info.loadIcon(manager));
                appInfo.setAppPackage(info.activityInfo.packageName);
                appInfo.setAppClass(info.activityInfo.name);
                appList.add(appInfo);
            }
        }
 
        return appList;
    }
 
    /**
     * 根据包名和Activity启动类查询应用信息
     *
     * @param cls
     * @param pkg
     * @return
     */
    public static AppInfo getAppByClsPkg(Context context, String pkg, String cls) {
        AppInfo appInfo = new AppInfo();
 
        PackageManager pm = context.getPackageManager();
        Drawable icon;
        CharSequence label = "";
        ComponentName comp = new ComponentName(pkg, cls);
        try {
            ActivityInfo info = pm.getActivityInfo(comp, 0);
            icon = pm.getApplicationIcon(info.applicationInfo);
            label = pm.getApplicationLabel(pm.getApplicationInfo(pkg, 0));
        } catch (NameNotFoundException e) {
            icon = pm.getDefaultActivityIcon();
        }
        appInfo.setAppClass(cls);
        appInfo.setAppIcon(icon);
        appInfo.setAppLable(label + "");
        appInfo.setAppPackage(pkg);
 
        return appInfo;
    }
 
    /**
     * 跳转到WIFI设置
     *
     * @param context
     */
    public static void intentWifiSetting(Context context) {
        if (android.os.Build.VERSION.SDK_INT > 10) {
            // 3.0以上打开设置界面,也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
            context.startActivity(new Intent(
                    android.provider.Settings.ACTION_SETTINGS));
        } else {
            context.startActivity(new Intent(
                    android.provider.Settings.ACTION_WIRELESS_SETTINGS));
        }
    }
 
    /**
     * WIFI网络开关
     *
     */
    public static void toggleWiFi(Context context, boolean enabled) {
        WifiManager wm = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        wm.setWifiEnabled(enabled);
    }
 
    /**
     * 移动网络开关
     */
    public static void toggleMobileData(Context context, boolean enabled) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        Class<!--?--> conMgrClass = null; // ConnectivityManager类
        Field iConMgrField = null; // ConnectivityManager类中的字段
        Object iConMgr = null; // IConnectivityManager类的引用
        Class<!--?--> iConMgrClass = null; // IConnectivityManager类
        Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法
        try {
            // 取得ConnectivityManager类
            conMgrClass = Class.forName(conMgr.getClass().getName());
            // 取得ConnectivityManager类中的对象mService
            iConMgrField = conMgrClass.getDeclaredField("mService");
            // 设置mService可访问
            iConMgrField.setAccessible(true);
            // 取得mService的实例化类IConnectivityManager
            iConMgr = iConMgrField.get(conMgr);
            // 取得IConnectivityManager类
            iConMgrClass = Class.forName(iConMgr.getClass().getName());
            // 取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法
            setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod(
                    "setMobileDataEnabled", Boolean.TYPE);
            // 设置setMobileDataEnabled方法可访问
            setMobileDataEnabledMethod.setAccessible(true);
            // 调用setMobileDataEnabled方法
            setMobileDataEnabledMethod.invoke(iConMgr, enabled);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * GPS开关 当前若关则打开 当前若开则关闭
     */
    public static void toggleGPS(Context context) {
        Intent gpsIntent = new Intent();
        gpsIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
        gpsIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
        } catch (CanceledException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 调节系统音量
     *
     * @param context
     */
    public static void holdSystemAudio(Context context) {
        AudioManager audiomanage = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
        // 获取系统最大音量
        // int maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 获取当前音量
        // int currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_RING);
        // 设置音量
        // audiomanage.setStreamVolume(AudioManager.STREAM_SYSTEM, currentVolume, AudioManager.FLAG_PLAY_SOUND);
         
        // 调节音量
        // ADJUST_RAISE 增大音量,与音量键功能相同
        // ADJUST_LOWER 降低音量
        audiomanage.adjustStreamVolume(AudioManager.STREAM_SYSTEM,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
 
    }
 
    /**
     * 设置亮度(每30递增)
     *
     * @param resolver
     * @param brightness
     */
    public static void setBrightness(Activity activity) {
        ContentResolver resolver = activity.getContentResolver();
        Uri uri = android.provider.Settings.System
                .getUriFor("screen_brightness");
        int nowScreenBri = getScreenBrightness(activity);
        nowScreenBri = nowScreenBri <= 225 ? nowScreenBri + 30 : 30;
        System.out.println("nowScreenBri==" + nowScreenBri);
        android.provider.Settings.System.putInt(resolver, "screen_brightness",
                nowScreenBri);
        resolver.notifyChange(uri, null);
    }
 
    /**
     * 获取屏幕的亮度
     *
     * @param activity
     * @return
     */
    public static int getScreenBrightness(Activity activity) {
        int nowBrightnessValue = 0;
        ContentResolver resolver = activity.getContentResolver();
        try {
            nowBrightnessValue = android.provider.Settings.System.getInt(
                    resolver, Settings.System.SCREEN_BRIGHTNESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nowBrightnessValue;
    }
 
    /**
     * 跳转到系统设置
     *
     * @param context
     */
    public static void intentSetting(Context context) {
        String pkg = "com.android.settings";
        String cls = "com.android.settings.Settings";
 
        ComponentName component = new ComponentName(pkg, cls);
        Intent intent = new Intent();
        intent.setComponent(component);
 
        context.startActivity(intent);
    }
     
    /**
     * 获取文件夹下所有文件
     * @param path
     * @return
     */
    public static ArrayList<file> getFilesArray(String path){
        File file = new File(path);
        File files[] = file.listFiles();
        ArrayList<file> listFile = new ArrayList<file>();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    listFile.add(files[i]);
                }
                if (files[i].isDirectory()) {
                    listFile.addAll(getFilesArray(files[i].toString()));
                }
            }
        }
        return listFile;
    }
     
    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图,然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND,则类型要使用MICRO_KIND作为kind的值,这样会节省内存。
     * @param videoPath 视频的路径
     * @param width 指定输出视频缩略图的宽度
     * @param height 指定输出视频缩略图的高度度
     * @param kind 参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *            其中,MINI_KIND: 512 x 384,MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */ 
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, 
            int kind) { 
        Bitmap bitmap = null; 
        // 获取视频的缩略图  
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind); 
        //System.out.println("w"+bitmap.getWidth()); 
        //System.out.println("h"+bitmap.getHeight()); 
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, 
                ThumbnailUtils.OPTIONS_RECYCLE_INPUT); 
        return bitmap; 
    }
     
    /**
     * 打开视频文件
     * @param context
     * @param file 视频文件
     */
    public static void intentVideo(Context context, File file){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String type = "video/*";
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, type);
        context.startActivity(intent);
    }
}
</file></file></file></appinfo></appinfo></resolveinfo></appinfo></appinfo></appinfo></resolveinfo></appinfo>

开机清除用户数据

添加开机广播

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.topwise.airlinemanager;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
 
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.IPackageDataObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
 
/**
 * 开机广播
 * @author XiaoSai
 *
 */
public class CleanDataReceiverd extends BroadcastReceiver {
 
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            //清除用户数据
            cleanUserData(context);
        }
    }
 
    class ClearUserDataObserver extends IPackageDataObserver.Stub {
        public void onRemoveCompleted(final String packageName,
                final boolean succeeded) {
 
        }
    }
 
    private void cleanUserData(Context context) {
        PackageManager manager = context.getPackageManager();
        List<packageinfo> packages = manager.getInstalledPackages(0);
 
        ClearUserDataObserver mClearDataObserver = new ClearUserDataObserver();
 
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
 
        Method targetMethod = null;
        Class<!--?--> temp = am.getClass();
        // String className = temp.getName();
        Method[] methods = temp.getMethods();
        for (int j = 0; j < methods.length; j++) {
            if (("clearApplicationUserData".equals(methods[j].getName()))) {
                targetMethod = methods[j];
                break;
            }
        }
 
        String pkg = null;
        if (packages != null && packages.size() > 0) {
            for (int i = 0; i < packages.size(); i++) {
                pkg = packages.get(i).packageName;
                if (pkg.equals("com.sina.weibotab")
                        || pkg.equals("com.tencent.android.pad")
                        || pkg.equals("com.tencent.hd.qq")
                        || pkg.equals("com.tencent.WBlog")
                        || pkg.equals("com.tencent.mm")) {
                    try {
                        targetMethod.invoke(am, pkg, mClearDataObserver);
                        Log.i("XIAOS", "clean pgk "+pkg);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
</packageinfo>

清除用户数据需要调用ActivityManager类中的clearApplicationUserData方法,但是这个方法被系统给隐藏类,调用不了,不过我们可以通过反射机制来调用
AndroidManifest.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.player.playlauncher" android:versioncode="1" android:versionname="1.0" android:shareduserid="android.uid.system">
 
    <uses-sdk android:minsdkversion="8" android:targetsdkversion="17">
 
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
    <uses-permission android:name="android.permission.CLEAR_APP_USER_DATA">
     
     
         
            <intent-filter>
                 
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
         
        <receiver android:name=".CleanDataReceiverd">
            <intent-filter>
                 
            </action></intent-filter>
        </receiver>
    </application>
 
</uses-permission></uses-permission></uses-sdk></manifest>

保存可能会报错,clean 一下项目就可以了
最后还需要在 Android.mk 中添加 一行

LOCAL_CERTIFICATE := platform

成功源于不断的学习和积累 !

转载于:https://www.cnblogs.com/hudabing/p/4708535.html

Android 系统工具类SystemUtils相关推荐

  1. Android开发工具类 Utils

    包括了各种工具类.辅助类.管理类等 Awesome_API: https://github.com/marktony/Awesome_API/blob/master/Chinese.md 收集中国国内 ...

  2. Android开发工具类

    包括了各种工具类.辅助类.管理类等 Awesome_API: https://github.com/marktony/Awesome_API/blob/master/Chinese.md 收集中国国内 ...

  3. android xitong工具,Android系统工具盘点

    经常使用电脑的一些朋友,多少会定期不定期地使用一些系统工具,比如超级兔子.优化大师之类的优化类软件.因为经常优化电脑,对自己电脑的运行速度以及系统的正常运行有极大帮助.当然,不用优化只喜欢重装电脑的用 ...

  4. android sharedpreferences工具类

    今天,简单讲讲如何写一个sharedpreferences的工具类. 很简单,把一些重复的操作封装在工具类里,其他地方调用就可以.在网上搜索了比较多的资料,找到一个比较好的工具类. 参考文章:http ...

  5. android sharedpreferences 工具类,android sharedpreferences工具类

    释放双眼,带上耳机,听听看~! 今天,简单讲讲如何写一个sharedpreferences的工具类. 很简单,把一些重复的操作封装在工具类里,其他地方调用就可以.在网上搜索了比较多的资料,找到一个比较 ...

  6. java 系统工具类 查询内存 CPU 系统基本信息 SysInfoUtils

    java 系统工具类 查询内存 CPU 系统基本信息 SysInfoUtils maven依赖 <dependency><groupId>com.github.oshi< ...

  7. 分享一些收集整理的一些常用Android万能工具类

    尊重原创  https://github.com/l123456789jy/Lazy 内容包括 AnimationUtils 动画工具类 AppUtils APP相关信息工具类 AssetDataba ...

  8. Android 常见工具类封装

    1,MD5工具类: public class MD5Util {public final static String MD5(String s) {char hexDigits[] = { '0', ...

  9. android 开发工具类,Android中常用开发工具类—持续更新...

    一.自定义ActionBar public class ActionBarTool { public static void setActionBarLayout(Activity act,Conte ...

最新文章

  1. 如何禁止页面被 jframe 引用_PD1该如何使用?靶向能否转用PD1?
  2. WebService SOAP、Restful和HTTP(post/get)请求区别
  3. PHP中session与cookie的简单使用
  4. 谷歌提议更改Istio指导委员会
  5. Python学习6 字典基础知识和常用函数
  6. android悬浮功能实现,Android实现系统级悬浮按钮
  7. matlab 矩阵位移法编程 结构力学,matlab 矩阵位移法编程 结构力学
  8. 马哥-Linux云计算架构班学习计划
  9. java需要了解的几个算法
  10. Vue-购物车简单案例
  11. RS_code 编码和解码
  12. python读取二进制文件_Python读写二进制文件
  13. 同类型的免费下载软件中, JDownloader的功能比FreeRapid Downloader功能要强很多
  14. nc65 树单据类型教程
  15. 计算机硬盘模式,详细教你bios设置硬盘模式
  16. JAVA设计模式之桥接模式
  17. Eclipse中没有Servers或Dynamic Web Project的解决方案
  18. 叉积的证明_矢量叉乘分配律的几何证明
  19. 团队中的“个人英雄主义”
  20. 高速文件服务器搭建教程,文件服务器配置教程.doc

热门文章

  1. 8.2.1.2 How MySQL Optimizes WHERE Clauses MySQL 优化WHERE 子句
  2. Android基本概念(一)
  3. [转] Transact_SQL手册
  4. cpp 条件判断 大于等于_第31p,if条件语句,请满足我的要求
  5. Logback 配置文件例子
  6. ASCII码表完整版
  7. python str byte编码_Python3中内置类型bytes和str用法及byte和string之间各种编码转换 问题...
  8. acwing算法题--多重背包问题二
  9. flannel源码分析--main
  10. leetcode算法题--预测赢家★