Android tool SystemUtils collection and sorting (continuous update), androidsystemutils

Source: Internet
Author: User

Android tool SystemUtils collection and sorting (continuous update), androidsystemutils

Recently, some system-related things have been involved in the functions, and a tool class has been collected and compiled on the Internet for convenient calling.

The following functions are available:

Obtain all apps in the system, obtain the APP installed by the user, query the APP information based on the package name and Activity startup class, jump to WIFI settings, WIFI network switch, mobile network switch, GPS switch if if this parameter is set to off, the system turns off When enabled, adjusts the system volume, sets the brightness, obtains the brightness of the screen, jumps to system settings, obtains all files in the folder, obtains thumbnails of the video, and opens the video file. ..

The tool categories will be updated continuously and we will learn and make progress together.


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. medi A. 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 {/*** obtain all system APP applications ** @ param context */public static ArrayList <AppInfo> getAllApp (Context context) {PackageManager manager = context. getPackageManager (); Intent m AinIntent = new Intent (Intent. ACTION_MAIN, null); mainIntent. addCategory (Intent. CATEGORY_LAUNCHER); List <ResolveInfo> apps = manager. queryIntentActivities (mainIntent, 0); // sort the obtained APP information by name. sort (apps, new ResolveInfo. displayNameComparator (manager); ArrayList <AppInfo> appList = new ArrayList <AppInfo> (); for (ResolveInfo info: apps) {AppInfo appInfo = new AppInfo (); appInfo. setAppLable (inf O. 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;}/*** get the APP installed by the user ** @ param context */pub Lic static ArrayList <AppInfo> 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); // sort the obtained APP information by name. sort (apps, new ResolveInfo. displayNameComparator (manager); ArrayList <AppInfo> PpList = new ArrayList <AppInfo> (); 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 ;} /*** query application information based on the package name and Activity startup class ** @ 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 (co Mp, 0); icon = pm. getApplicationIcon (info. applicationInfo); label = pm. getApplicationLabel (pm. getApplicationInfo (pkg, 0);} catch (NameNotFoundException e) {icon = pm. getdefaactivactivityicon ();} appInfo. setAppClass (cls); appInfo. setAppIcon (icon); appInfo. setAppLable (label + ""); appInfo. setAppPackage (pkg); return appInfo;}/*** jump to WIFI settings ** @ param context */public static void intentWifiSetting (Context co Ntext) {if (android. OS. build. VERSION. SDK_INT> 10) {// 3.0 or above to open the settings page. You can also use ACTION_WIRELESS_SETTINGS to open the wifi interface context. startActivity (new Intent (android. provider. settings. ACTION_SETTINGS);} else {context. startActivity (new Intent (android. provider. settings. ACTION_WIRELESS_SETTINGS);}/*** WIFI network switch **/public static void toggleWiFi (Context context, boolean enabled) {WifiManager wm = (WifiManager) contex T. getSystemService (Context. WIFI_SERVICE); wm. setWifiEnabled (enabled);}/*** mobile network switch */public static void toggleMobileData (Context context, boolean enabled) {ConnectivityManager conMgr = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); Class <?> ConMgrClass = null; // ConnectivityManager Class Field iConMgrField = null; // The Field Object iConMgr = null in the ConnectivityManager Class; // reference Class of the IConnectivityManager Class <?> IConMgrClass = null; // IConnectivityManager Class Method setMobileDataEnabledMethod = null; // setMobileDataEnabled Method try {// get ConnectivityManager Class conMgrClass = Class. forName (conMgr. getClass (). getName (); // get the object mServiceiConMgrField = conMgrClass in the ConnectivityManager class. getDeclaredField ("mService"); // you can set mService to access iConMgrField. setAccessible (true); // get the mService instantiation class IConnectivityManageriConMgr = iConMgrFiel D. get (conMgr); // get IConnectivityManager Class iConMgrClass = Class. forName (iConMgr. getClass (). getName (); // obtain the setMobileDataEnabled (boolean) method in the IConnectivityManager class setMobileDataEnabledMethod = iConMgrClass. getDeclaredMethod ("setMobileDataEnabled", Boolean. TYPE); // set the setMobileDataEnabled method to access setMobileDataEnabledMethod. setAccessible (true); // call the setMobileDataEnabled method setMobileDataEnabledMethod. invoke (iConMg R, 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 () ;}}/*** If the GPS switch is off, turn on the current switch. If enabled, turn off */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 (CanceledE Xception e) {e. printStackTrace () ;}}/*** adjust system volume ** @ param context */public static void holdSystemAudio (Context context) {AudioManager audiomanage = (AudioManager) context. getSystemService (Context. AUDIO_SERVICE); // obtain the maximum volume of the system // int maxVolume = audiomanage. getStreamMaxVolume (AudioManager. STREAM_MUSIC); // get the current volume // int currentVolume = audiomanage. getStreamVolume (AudioManager. STREAM_RING); // set the volume // au Diomanage. setStreamVolume (AudioManager. STREAM_SYSTEM, currentVolume, AudioManager. FLAG_PLAY_SOUND); // adjust the volume // ADJUST_RAISE increases the volume, which is the same as the volume key function. // ADJUST_LOWER reduces the volume of audiomanage. adjustStreamVolume (AudioManager. STREAM_SYSTEM, AudioManager. ADJUST_RAISE, AudioManager. FLAG_SHOW_UI);}/*** sets the brightness (increasing every 30 seconds) ** @ param resolver * @ param brightness */public static void setBrightness (Activity activity) {ContentResolver re Solver = 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);}/*** get screen brightness ** @ param activity * @ return */public static int getScreenBrightness (Activity activity) {int nowBrightnessValue = 0; contentResolver resolver = activity. getContentResolver (); try {nowBrightnessV Alue = android. provider. settings. system. getInt (resolver, Settings. system. SCREEN_BRIGHTNESS);} catch (Exception e) {e. printStackTrace ();} return nowBrightnessValue;}/*** jump to system settings ** @ 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);}/*** get all files in the folder * @ 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;}/*** get the video thumbnail * use ThumbnailUtils to create a thumbnail of the video, then, use ThumbnailUtils to generate a thumbnail of the specified size. * If the width and height of the desired thumbnail are smaller than that of MICRO_KIND, use MICRO_KIND as the kind value, which saves memory. * @ Param videoPath the video path * @ param width specifies the width of the output video thumbnail * @ param height specifies the height of the output video thumbnail * @ param kind refer to MediaStore. images. the constants MINI_KIND and MICRO_KIND In the Thumbnails class. * MINI_KIND: 512x384, MICRO_KIND: 96x96 * @ return specifies the video thumbnail size */public static Bitmap getVideoThumbnail (String videoPath, int width, int height, int kind) {Bitmap bitmap = null; // obtain the video thumbnail 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;}/*** open the video file * @ param context * @ param File video 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 );}}


Clear user data at startup

Add boot Broadcast

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. packageManage R; import android. util. log;/*** boot broadcast ** @ author XiaoSai **/public class CleanDataReceiverd extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {if (intent. getAction (). equals (Intent. ACTION_BOOT_COMPLETED) {// CLEAR user data 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 ();}}}}}}

To clear user data, you need to call the clearApplicationUserData method in the ActivityManager class. However, this method cannot be called because it is hidden by the system. However, we can call this method through the reflection mechanism.

AndroidManifest. xml

<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"/>        <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity             android:name="com.player.playlauncher.FirstLevel"            android:label="@string/app_name"            android:icon="@drawable/ic_launcher">            <intent-filter >                <action android:name="android.intent.action.MAIN"/>                <category android:name="android.intent.category.LAUNCHER"/>            </intent-filter>        </activity>                <receiver             android:name=".CleanDataReceiverd">            <intent-filter>                <action android:name="android.intent.action.BOOT_COMPLETED" />            </intent-filter>        </receiver>    </application></manifest>

An error may be reported when saving. Just clean the project.

Add a line in Android. mk.

LOCAL_CERTIFICATE: = platform


Success comes from continuous learning and accumulation!




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.