Collect and organize Android tool SystemUtils (continuous update)

Source: Internet
Author: User

Collect and organize Android tool SystemUtils (continuous update)

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. 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 {/*** obtain all system apps ** @ 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
 
  
Apps = manager. queryIntentActivities (mainIntent, 0); // sort the obtained APP information by name. 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;}/*** get the APP installed by the user ** @ 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
  
   
Apps = manager. queryIntentActivities (mainIntent, 0); // sort the obtained APP information by name. 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 ;} /*** 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 (comp, 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 context) {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) context. 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 = iConMgrField. 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 (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 (); }/*** If the current GPS switch is off, turn it on. If the current switch is on, 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 (CanceledEx Ception 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 // aud Iomanage. 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 res Olver = 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 {nowBrightnessValue = 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
   
    
GetFilesArray (String path) {File file = new File (path); File files [] = file. listFiles (); ArrayList
    
     
ListFile = new ArrayList
     
      
(); 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. packageManager; 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
 
  
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

     
      
      
                              
                                  
               
                          
              
                               
           
      
 

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.