Android开发代码片收集

以下片段收集自: http://blog.csdn.net/zhangjg_blog/article/details/27697665


不能保证代码片段没有bug, 在使用时需要经过测试.


1 切换系统中某个组件的状态,设置其enable或disable

[java]  view plain copy
  1. public void toggleComponent(View view){  
  2.   
  3.         PackageManager pm = getPackageManager();  
  4.   
  5.         String pkgName = "com.aa.activitytest";  
  6.         String comName = "com.aa.activitytest.SecondActivity";  
  7.         ComponentName componentName = new ComponentName(pkgName, comName);  
  8.   
  9.         int state = pm.getComponentEnabledSetting(componentName);  
  10.   
  11.         boolean isEnable = state == PackageManager.COMPONENT_ENABLED_STATE_ENABLED  
  12.                 || state == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;  
  13.   
  14.   
  15.         if(isEnable){  
  16.             pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);  
  17.         }else {  
  18.             pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);  
  19.         }  
  20.     }  


2 列出系统中所有安装的app的信息

[java]  view plain copy
  1. PackageManager pm = getPackageManager();  
  2. List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);  
  3.   
  4. for(PackageInfo packageInfo : packages){  
  5.       
  6.     //应用图标  
  7.     Drawable icon = packageInfo.applicationInfo.loadIcon(pm);  
  8.       
  9.     //标题  
  10.     CharSequence lable = packageInfo.applicationInfo.loadLabel(pm);  
  11.       
  12.     //包名  
  13.     String packageName = packageInfo.packageName;  
  14.       
  15. }  


3 将raw中的apk拷贝到/data/data/包名/files/中


[java]  view plain copy
  1. //1 拷贝raw中的apk文件  
  2.         InputStream in = null;  
  3.         OutputStream out = null;  
  4.   
  5.         try {  
  6.             in = getResources().openRawResource(R.raw.dex_apk);  
  7.             out = this.openFileOutput("dex_apk.apk", Context.MODE_PRIVATE);  
  8.             copyFile(in, out);  
  9.         } catch (FileNotFoundException e) {  
  10.             e.printStackTrace();  
  11.         }finally {  
  12.             try {  
  13.                 if (in != null) in.close();  
  14.             }catch (IOException e){}  
  15.   
  16.             try{  
  17.                 if (out != null) out.close();  
  18.             }catch (IOException e){}  
  19.         }  

4 拷贝文件


[java]  view plain copy
  1. private void copyFile(InputStream in, OutputStream out){  
  2.   
  3.     byte[] buffer = new byte[1024];  
  4.     int len = 0;  
  5.   
  6.     try {  
  7.         while((len = in.read(buffer) ) != -1){  
  8.             out.write(buffer , 0 , len);  
  9.         }  
  10.     } catch (IOException e) {  
  11.         e.printStackTrace();  
  12.     }  
  13.   
  14. }  

5 使用DexClassLoader加载 /data/data/包名/files/ 下的apk的classes.dex , 并通过反射执行。 


[java]  view plain copy
  1. //2 加载并执行apk中的类  
  2. String pkgDataPath = "/data/data/" + getPackageName();  
  3. String optimizedDirectory = pkgDataPath + "/files/";  
  4. String dexPath = optimizedDirectory + "dex_apk.apk";  
  5.   
  6. DexClassLoader dexClassLoader = new DexClassLoader(dexPath, optimizedDirectory, nullthis.getClassLoader());  
  7.   
  8. try {  
  9.     Class personClazz = dexClassLoader.loadClass("com.aa.dexapk.Person");  
  10.   
  11.     Object newInstance = personClazz.newInstance();  
  12.   
  13.     Method method = personClazz.getMethod("doWork");  
  14.   
  15.     method.invoke(newInstance);  
  16. catch (Exception e) {  
  17.     e.printStackTrace();  
  18. }  


6 动态加载其他已经安装的apk的dex文件, 并通过反射执行


[java]  view plain copy
  1. private void useDexClassLoader(){  
  2.             //创建一个意图,用来找到指定的apk  
  3.             Intent intent = new Intent("com.suchangli.android.plugin"null);  
  4.             //获得包管理器  
  5.             PackageManager pm = getPackageManager();  
  6.             List<ResolveInfo> resolveinfoes =  pm.queryIntentActivities(intent, 0);  
  7.             //获得指定的activity的信息  
  8.             ActivityInfo actInfo = resolveinfoes.get(0).activityInfo;  
  9.               
  10.             //获得包名  
  11.             String pacageName = actInfo.packageName;  
  12.             //获得apk的目录或者jar的目录  
  13.             String apkPath = actInfo.applicationInfo.sourceDir;  
  14.             //dex解压后的目录,注意,这个用宿主程序的目录,android中只允许程序读取写自己  
  15.             //目录下的文件  
  16.             String dexOutputDir = getApplicationInfo().dataDir;  
  17.               
  18.             //native代码的目录  
  19.             String libPath = actInfo.applicationInfo.nativeLibraryDir;  
  20.             //创建类加载器,把dex加载到虚拟机中  
  21.             DexClassLoader calssLoader = new DexClassLoader(apkPath, dexOutputDir, libPath,  
  22.                             this.getClass().getClassLoader());  
  23.               
  24.             //利用反射调用插件包内的类的方法  
  25.               
  26.             try {  
  27.                         Class<?> clazz = calssLoader.loadClass(pacageName+".Plugin1");  
  28.                           
  29.                         Object obj = clazz.newInstance();  
  30.                         Class[] param = new Class[2];  
  31.                         param[0] = Integer.TYPE;  
  32.                         param[1] = Integer.TYPE;  
  33.                           
  34.                         Method method = clazz.getMethod("function1", param);  
  35.                           
  36.                         Integer ret = (Integer)method.invoke(obj, 1,12);  
  37.                           
  38.                         Log.i("Host""return result is " + ret);  
  39.                           
  40.                 } catch (ClassNotFoundException e) {  
  41.                         e.printStackTrace();  
  42.                 } catch (InstantiationException e) {  
  43.                         e.printStackTrace();  
  44.                 } catch (IllegalAccessException e) {  
  45.                         e.printStackTrace();  
  46.                 } catch (NoSuchMethodException e) {  
  47.                         e.printStackTrace();  
  48.                 } catch (IllegalArgumentException e) {  
  49.                         e.printStackTrace();  
  50.                 } catch (InvocationTargetException e) {  
  51.                         e.printStackTrace();  
  52.                 }  
  53.     }  


7 获取其他包中的资源(pm.getResourcesForApplication(pkgName) )

[java]  view plain copy
  1. Intent intent = new Intent("com.suchangli.android.plugin"null);    
  2.         //获得包管理器    
  3.         PackageManager pm = getPackageManager();    
  4.         List<ResolveInfo> resolveinfoes =  pm.queryIntentActivities(intent, 0);    
  5.         //获得指定的activity的信息    
  6.         ActivityInfo actInfo = resolveinfoes.get(0).activityInfo;    
  7.             
  8.         //获得包名    
  9.         String pacageName = actInfo.packageName;    
  10.              
  11.         try {    
  12.             Resources res = pm.getResourcesForApplication(pacageName);    
  13.                 
  14.             int id = 0;    
  15.             id = res.getIdentifier("ic_launcher""drawable", pacageName);    
  16.             Log.i("""resId is " + id);    
  17.                 
  18.                 
  19.         } catch (NameNotFoundException e) {    
  20.             e.printStackTrace();    
  21.         }    


8 Context.getDir创建并返回目录


Context.getDir(“mydir”) 返回的目录的绝对路径是 :  /data/data/package_name/app_mydir 。 


9 获取Activity的图标


[java]  view plain copy
  1. private Bitmap getIconForActivity(Context context, String packageName, String activityName){  
  2.       
  3.     ComponentName activityComp = new ComponentName(packageName, activityName);  
  4.     PackageManager pm = context.getPackageManager();  
  5.   
  6.     Intent intentToResolve = new Intent();  
  7.     intentToResolve.setComponent(activityComp);  
  8.   
  9.     ResolveInfo resolveInfo = pm.resolveActivity(intentToResolve, 0);  
  10.   
  11.     Drawable iconDrawable = resolveInfo.activityInfo.loadIcon(pm);  
  12.   
  13.     return Utilities.createIconBitmap( iconDrawable, context);  
  14. }  

其中Utilities为Launcher中的工具类。 


10 获取当前app的签名信息:


[java]  view plain copy
  1. /** 
  2.  * get signature of current package 
  3.  * @param context 
  4.  * @return signature, null if there is no signature 
  5.  */  
  6. public static String getSignature(Context context){  
  7.   
  8.     Log.i(TAG, "SignatureUtils.getSignature");  
  9.   
  10.     PackageManager pm = context.getPackageManager();  
  11.     String pkgName = context.getPackageName();  
  12.   
  13.     try {  
  14.         PackageInfo pi = pm.getPackageInfo(pkgName, PackageManager.GET_SIGNATURES);  
  15.         Signature[] signatures = pi.signatures;  
  16.   
  17.         if(signatures != null && signatures.length > 0){  
  18.   
  19.             String signature =  signatures[0].toCharsString();  
  20.             Log.i(TAG, "Signature of current package is : " + signature);  
  21.   
  22.             return  signature;  
  23.         }  
  24.     } catch (PackageManager.NameNotFoundException e1) {  
  25.         e1.printStackTrace();  
  26.     }  
  27.   
  28.     return null;  
  29. }  



11 获取apk文件的签名信息(未安装, 只是一个apk文件)


[java]  view plain copy
  1. /** 
  2.  * get signature of an apk file 
  3.  * this method will execute quit a long time, so it is suitable to call it in sub thread 
  4.  * @param context 
  5.  * @param apkFilePath 
  6.  * @return signature , null if there is no signature , or apkFilePath is wrong 
  7.  */  
  8. public static String getSignatureOfApk(Context context, String apkFilePath){  
  9.     Log.i(TAG, "SignatureUtils.getSignatureOfApk");  
  10.   
  11.     if (TextUtils.isEmpty(apkFilePath)) return null;  
  12.   
  13.     PackageManager pm = context.getPackageManager();  
  14.   
  15.   
  16.     PackageInfo pi = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_SIGNATURES);  
  17.     Signature[] signatures = pi.signatures;  
  18.   
  19.     if(signatures != null && signatures.length > 0){  
  20.   
  21.         String signature =  signatures[0].toCharsString();  
  22.         Log.i(TAG, "Signature of " + apkFilePath + " is : " + signature);  
  23.   
  24.         return  signature;  
  25.     }  
  26.   
  27.   
  28.     return null;  
  29. }  


12 获取apk文件的权限信息


[java]  view plain copy
  1. public static List<PermissionInfo> getApkPermissions(String apkFile, PackageManager pm){  
  2.   
  3.      if(DEBUG) Log.i(TAG, "PackageUtils.getApkPermissions");  
  4.   
  5.      List<PermissionInfo> permissionInfos = new ArrayList<PermissionInfo>();  
  6.   
  7.      PackageInfo packageInfo =  pm.getPackageArchiveInfo(apkFile, PackageManager.GET_PERMISSIONS);  
  8.   
  9.      String[] permissions = packageInfo.requestedPermissions;  
  10.   
  11.      for(String permName : permissions ){  
  12.   
  13.          try {  
  14.              PermissionInfo permissionInfo = pm.getPermissionInfo(permName, 0);  
  15.              permissionInfos.add(permissionInfo);  
  16.   
  17.          } catch (PackageManager.NameNotFoundException e) {  
  18.              e.printStackTrace();  
  19.          }  
  20.      }  
  21.   
  22.      return permissionInfos;  

你可能感兴趣的:(Android开发代码片收集)