Android 开发中的一些小技巧


dip转px
  1. public int convertDipOrPx(int dip) {  
  2.     float scale = MarketApplication.getMarketApplicationContext()  
  3.             .getResources().getDisplayMetrics().density;  
  4.     return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));  
  5. }  
    public int convertDipOrPx(int dip) {
        float scale = MarketApplication.getMarketApplicationContext()
                .getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }
获取当前窗体,并添加自定义view:
  1. getWindowManager()  
  2.                 .addView(  
  3.                         overlay,  
  4.                         new WindowManager.LayoutParams(  
  5.                                 LayoutParams.WRAP_CONTENT,  
  6.                                 LayoutParams.WRAP_CONTENT,  
  7.                                 WindowManager.LayoutParams.TYPE_APPLICATION,  
  8.                                 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  
  9.                                         | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,  
  10.                                 PixelFormat.TRANSLUCENT));  
getWindowManager()
                .addView(
                        overlay,
                        new WindowManager.LayoutParams(
                                LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT,
                                WindowManager.LayoutParams.TYPE_APPLICATION,
                                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                                PixelFormat.TRANSLUCENT));
自定义fastScrollBar图片样式:
  1. try {  
  2.     Field f = AbsListView.class.getDeclaredField("mFastScroller");  
  3.     f.setAccessible(true);  
  4.     Object o = f.get(listView);  
  5.     f = f.getType().getDeclaredField("mThumbDrawable");  
  6.     f.setAccessible(true);  
  7.     Drawable drawable = (Drawable) f.get(o);  
  8.     drawable = getResources().getDrawable(R.drawable.ic_launcher);  
  9.     f.set(o, drawable);  
  10.     Toast.makeText(this, f.getType().getName(), 1000).show();  
  11. catch (Exception e) {  
  12.     throw new RuntimeException(e);  
  13. }  
        try {
            Field f = AbsListView.class.getDeclaredField("mFastScroller");
            f.setAccessible(true);
            Object o = f.get(listView);
            f = f.getType().getDeclaredField("mThumbDrawable");
            f.setAccessible(true);
            Drawable drawable = (Drawable) f.get(o);
            drawable = getResources().getDrawable(R.drawable.ic_launcher);
            f.set(o, drawable);
            Toast.makeText(this, f.getType().getName(), 1000).show();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

=网络==================================

判断网络是否可用:
  1. /** 
  2.      * 网络是否可用 
  3.      *  
  4.      * @param context 
  5.      * @return 
  6.      */  
  7.     public static boolean isNetworkAvailable(Context context) {  
  8.         ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  9.         NetworkInfo[] info = mgr.getAllNetworkInfo();  
  10.         if (info != null) {  
  11.             for (int i = 0; i < info.length; i++) {  
  12.                 if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
  13.                     return true;  
  14.                 }  
  15.             }  
  16.         }  
  17.         return false;  
  18.     }  
/**
	 * 网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info = mgr.getAllNetworkInfo();
	    if (info != null) {
	    	for (int i = 0; i < info.length; i++) {
	    		if (info[i].getState() == NetworkInfo.State.CONNECTED) {
	    			return true;
	    		}
	    	}
	    }
		return false;
	}

方法二:

  1. /* 
  2.  * 判断网络连接是否已开 2012-08-20true 已打开 false 未打开 
  3.  */  
  4. public static boolean isConn(Context context) {  
  5.     boolean bisConnFlag = false;  
  6.     ConnectivityManager conManager = (ConnectivityManager) context  
  7.             .getSystemService(Context.CONNECTIVITY_SERVICE);  
  8.     NetworkInfo network = conManager.getActiveNetworkInfo();  
  9.     if (network != null) {  
  10.         bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();  
  11.     }  
  12.     return bisConnFlag;  
  13. }  
    /*
     * 判断网络连接是否已开 2012-08-20true 已打开 false 未打开
     */
    public static boolean isConn(Context context) {
        boolean bisConnFlag = false;
        ConnectivityManager conManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null) {
            bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }
判断是不是Wifi连接:
  1. public static boolean isWifiActive(Context icontext) {  
  2.     Context context = icontext.getApplicationContext();  
  3.     ConnectivityManager connectivity = (ConnectivityManager) context  
  4.             .getSystemService(Context.CONNECTIVITY_SERVICE);  
  5.     NetworkInfo[] info;  
  6.     if (connectivity != null) {  
  7.         info = connectivity.getAllNetworkInfo();  
  8.         if (info != null) {  
  9.             for (int i = 0; i < info.length; i++) {  
  10.                 if (info[i].getTypeName().equals("WIFI")  
  11.                         && info[i].isConnected()) {  
  12.                     return true;  
  13.                 }  
  14.             }  
  15.         }  
  16.     }  
  17.     return false;  
  18. }  
    public static boolean isWifiActive(Context icontext) {
        Context context = icontext.getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] info;
        if (connectivity != null) {
            info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getTypeName().equals("WIFI")
                            && info[i].isConnected()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
判断当前网络类型
  1. /** 
  2.      * 网络方式检查 
  3.      */  
  4.     private static int netCheck(Context context) {  
  5.         ConnectivityManager conMan = (ConnectivityManager) context  
  6.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  7.         State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)  
  8.                 .getState();  
  9.         State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)  
  10.                 .getState();  
  11.         if (wifi.equals(State.CONNECTED)) {  
  12.             return DO_WIFI;  
  13.         } else if (mobile.equals(State.CONNECTED)) {  
  14.             return DO_3G;  
  15.         } else {  
  16.             return NO_CONNECTION;  
  17.         }  
  18.     }  
/**
	 * 网络方式检查
	 */
	private static int netCheck(Context context) {
		ConnectivityManager conMan = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (wifi.equals(State.CONNECTED)) {
			return DO_WIFI;
		} else if (mobile.equals(State.CONNECTED)) {
			return DO_3G;
		} else {
			return NO_CONNECTION;
		}
	}


获取下载文件的真实名字
  1. public String getReallyFileName(String url) {  
  2.     StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
  3.             .detectDiskReads().detectDiskWrites().detectNetwork() // 这里可以替换为detectAll()  
  4.                                                                   // 就包括了磁盘读写和网络I/O  
  5.             .penaltyLog() // 打印logcat,当然也可以定位到dropbox,通过文件保存相应的log  
  6.             .build());  
  7.     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
  8.             .detectLeakedSqlLiteObjects() // 探测SQLite数据库操作  
  9.             .penaltyLog() // 打印logcat  
  10.             .penaltyDeath().build());  
  11.   
  12.     String filename = "";  
  13.     URL myURL;  
  14.     HttpURLConnection conn = null;  
  15.     if (url == null || url.length() < 1) {  
  16.         return null;  
  17.     }  
  18.   
  19.     try {  
  20.         myURL = new URL(url);  
  21.         conn = (HttpURLConnection) myURL.openConnection();  
  22.         conn.connect();  
  23.         conn.getResponseCode();  
  24.         URL absUrl = conn.getURL();// 获得真实Url  
  25.         // 打印输出服务器Header信息  
  26.         // Map<String, List<String>> map = conn.getHeaderFields();  
  27.         // for (String str : map.keySet()) {  
  28.         // if (str != null) {  
  29.         // Log.e("H3c", str + map.get(str));  
  30.         // }  
  31.         // }  
  32.         filename = conn.getHeaderField("Content-Disposition");// 通过Content-Disposition获取文件名,这点跟服务器有关,需要灵活变通  
  33.         if (filename == null || filename.length() < 1) {  
  34.             filename = URLDecoder.decode(absUrl.getFile(), "UTF-8");  
  35.         }  
  36.     } catch (MalformedURLException e) {  
  37.         e.printStackTrace();  
  38.     } catch (IOException e) {  
  39.         e.printStackTrace();  
  40.     } finally {  
  41.         if (conn != null) {  
  42.             conn.disconnect();  
  43.             conn = null;  
  44.         }  
  45.     }  
  46.   
  47.     return filename;  
  48. }  
    public String getReallyFileName(String url) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork() // 这里可以替换为detectAll()
                                                                      // 就包括了磁盘读写和网络I/O
                .penaltyLog() // 打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() // 探测SQLite数据库操作
                .penaltyLog() // 打印logcat
                .penaltyDeath().build());

        String filename = "";
        URL myURL;
        HttpURLConnection conn = null;
        if (url == null || url.length() < 1) {
            return null;
        }

        try {
            myURL = new URL(url);
            conn = (HttpURLConnection) myURL.openConnection();
            conn.connect();
            conn.getResponseCode();
            URL absUrl = conn.getURL();// 获得真实Url
            // 打印输出服务器Header信息
            // Map<String, List<String>> map = conn.getHeaderFields();
            // for (String str : map.keySet()) {
            // if (str != null) {
            // Log.e("H3c", str + map.get(str));
            // }
            // }
            filename = conn.getHeaderField("Content-Disposition");// 通过Content-Disposition获取文件名,这点跟服务器有关,需要灵活变通
            if (filename == null || filename.length() < 1) {
                filename = URLDecoder.decode(absUrl.getFile(), "UTF-8");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

        return filename;
    }

=图片==========================

bitmap转Byte数组(微信分享就需要用到)
  1. public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {  
  2.         ByteArrayOutputStream output = new ByteArrayOutputStream();  
  3.         bmp.compress(CompressFormat.PNG, 100, output);  
  4.         if (needRecycle) {  
  5.             bmp.recycle();  
  6.         }  
  7.   
  8.         byte[] result = output.toByteArray();  
  9.         try {  
  10.             output.close();  
  11.         } catch (Exception e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.   
  15.         return result;  
  16.     }  
public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
Resources转Bitmap
  1. public Bitmap loadBitmap(Resources res, int id) {  
  2.         BitmapFactory.Options opt = new BitmapFactory.Options();  
  3.         opt.inPreferredConfig = Bitmap.Config.RGB_565;  
  4.         opt.inPurgeable = true;  
  5.         opt.inInputShareable = true;  
  6.   
  7.         InputStream is = res.openRawResource(id);// 获取资源图片  
  8.         return BitmapFactory.decodeStream(is, null, opt);  
  9.     }  
public Bitmap loadBitmap(Resources res, int id) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;

        InputStream is = res.openRawResource(id);// 获取资源图片
        return BitmapFactory.decodeStream(is, null, opt);
    }
保存图片到SD卡
  1. public void saveBitmapToFile(String url, String filePath) {  
  2.         File iconFile = new File(filePath);  
  3.         if (!iconFile.getParentFile().exists()) {  
  4.             iconFile.getParentFile().mkdirs();  
  5.         }  
  6.   
  7.         if (iconFile.exists() && iconFile.length() > 0) {  
  8.             return;  
  9.         }  
  10.   
  11.         FileOutputStream fos = null;  
  12.         InputStream is = null;  
  13.         try {  
  14.             fos = new FileOutputStream(filePath);  
  15.             is = new URL(url).openStream();  
  16.   
  17.             int data = is.read();  
  18.             while (data != -1) {  
  19.                 fos.write(data);  
  20.                 data = is.read();  
  21.             }  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         } finally {  
  25.             try {  
  26.                 if (is != null) {  
  27.                     is.close();  
  28.                 }  
  29.                 if (fos != null) {  
  30.                     fos.close();  
  31.                 }  
  32.             } catch (IOException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.         }  
  36.     }  
public void saveBitmapToFile(String url, String filePath) {
        File iconFile = new File(filePath);
        if (!iconFile.getParentFile().exists()) {
            iconFile.getParentFile().mkdirs();
        }

        if (iconFile.exists() && iconFile.length() > 0) {
            return;
        }

        FileOutputStream fos = null;
        InputStream is = null;
        try {
            fos = new FileOutputStream(filePath);
            is = new URL(url).openStream();

            int data = is.read();
            while (data != -1) {
                fos.write(data);
                data = is.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

=系统==============================

根据包名打开一个应用程序
  1. public boolean openApp(String packageName) {  
  2.     PackageInfo pi = null;  
  3.     try {  
  4.         pi = mPM.getPackageInfo(packageName, 0);  
  5.     } catch (NameNotFoundException e) {  
  6.         e.printStackTrace();  
  7.         return false;  
  8.     }  
  9.   
  10.     if (pi == null) {  
  11.         return false;  
  12.     }  
  13.   
  14.     Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);  
  15.     resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
  16.     resolveIntent.setPackage(pi.packageName);  
  17.   
  18.     List<ResolveInfo> apps = mPM.queryIntentActivities(resolveIntent, 0);  
  19.   
  20.     ResolveInfo ri = null;  
  21.     try {  
  22.         ri = apps.iterator().next();  
  23.     } catch (Exception e) {  
  24.         return true;  
  25.     }  
  26.     if (ri != null) {  
  27.         String tmpPackageName = ri.activityInfo.packageName;  
  28.         String className = ri.activityInfo.name;  
  29.   
  30.         Intent intent = new Intent(Intent.ACTION_MAIN);  
  31.         intent.addCategory(Intent.CATEGORY_LAUNCHER);  
  32.   
  33.         ComponentName cn = new ComponentName(tmpPackageName, className);  
  34.   
  35.         intent.setComponent(cn);  
  36.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  37.         MarketApplication.getMarketApplicationContext().startActivity(  
  38.                 intent);  
  39.     } else {  
  40.         return false;  
  41.     }  
  42.     return true;  
  43. }  
    public boolean openApp(String packageName) {
        PackageInfo pi = null;
        try {
            pi = mPM.getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }

        if (pi == null) {
            return false;
        }

        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pi.packageName);

        List<ResolveInfo> apps = mPM.queryIntentActivities(resolveIntent, 0);

        ResolveInfo ri = null;
        try {
            ri = apps.iterator().next();
        } catch (Exception e) {
            return true;
        }
        if (ri != null) {
            String tmpPackageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(tmpPackageName, className);

            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            MarketApplication.getMarketApplicationContext().startActivity(
                    intent);
        } else {
            return false;
        }
        return true;
    }
判断是否APK是否安装过
  1. public boolean checkApkExist(Context context, String packageName) {  
  2.         if (packageName == null || "".equals(packageName))  
  3.             return false;  
  4.         try {  
  5.             ApplicationInfo info = context.getPackageManager()  
  6.                     .getApplicationInfo(packageName,  
  7.                             PackageManager.GET_UNINSTALLED_PACKAGES);  
  8.             return true;  
  9.         } catch (NameNotFoundException e) {  
  10.             return false;  
  11.         } catch (NullPointerException e) {  
  12.             return false;  
  13.         }  
  14.     }  
public boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName,
                            PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        } catch (NullPointerException e) {
            return false;
        }
    }
安装APK
  1. public void installApk(Context context, String strFileAllName) {  
  2.     File file = new File(strFileAllName);  
  3.     Intent intent = new Intent();  
  4.     intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  5.     intent.setAction(Intent.ACTION_VIEW);  
  6.     String type = "application/vnd.android.package-archive";  
  7.     intent.setDataAndType(Uri.fromFile(file), type);  
  8.     context.startActivity(intent);  
  9. }  
    public void installApk(Context context, String strFileAllName) {
        File file = new File(strFileAllName);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        intent.setDataAndType(Uri.fromFile(file), type);
        context.startActivity(intent);
    }
卸载APK
  1. public void UninstallApk(Context context, String strPackageName) {  
  2.     Uri packageURI = Uri.parse("package:" + strPackageName);  
  3.     Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);  
  4.     context.startActivity(uninstallIntent);  
  5. }  
    public void UninstallApk(Context context, String strPackageName) {
        Uri packageURI = Uri.parse("package:" + strPackageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        context.startActivity(uninstallIntent);
    }
判断SD卡是否可用
  1. public boolean CheckSD() {  
  2.     if (android.os.Environment.getExternalStorageState().equals(  
  3.             android.os.Environment.MEDIA_MOUNTED)) {  
  4.         return true;  
  5.     } else {  
  6.         return false;  
  7.     }  
  8. }  
    public boolean CheckSD() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
创建快捷方式:
  1. public void createShortCut(Context contxt) {  
  2.     // if (isInstallShortcut()) {// 如果已经创建了一次就不会再创建了  
  3.     // return;  
  4.     // }  
  5.   
  6.     Intent sIntent = new Intent(Intent.ACTION_MAIN);  
  7.     sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载  
  8.     sIntent.setClass(contxt, Login.class);  
  9.   
  10.     Intent installer = new Intent();  
  11.     installer.putExtra("duplicate"false);  
  12.     installer.putExtra("android.intent.extra.shortcut.INTENT", sIntent);  
  13.     installer.putExtra("android.intent.extra.shortcut.NAME""名字");  
  14.     installer.putExtra("android.intent.extra.shortcut.ICON_RESOURCE",  
  15.             Intent.ShortcutIconResource  
  16.                     .fromContext(contxt, R.drawable.icon));  
  17.     installer.setAction("com.android.launcher.action.INSTALL_SHORTCUT");  
  18.     contxt.sendBroadcast(installer);  
  19. }  
    public void createShortCut(Context contxt) {
        // if (isInstallShortcut()) {// 如果已经创建了一次就不会再创建了
        // return;
        // }

        Intent sIntent = new Intent(Intent.ACTION_MAIN);
        sIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 加入action,和category之后,程序卸载的时候才会主动将该快捷方式也卸载
        sIntent.setClass(contxt, Login.class);

        Intent installer = new Intent();
        installer.putExtra("duplicate", false);
        installer.putExtra("android.intent.extra.shortcut.INTENT", sIntent);
        installer.putExtra("android.intent.extra.shortcut.NAME", "名字");
        installer.putExtra("android.intent.extra.shortcut.ICON_RESOURCE",
                Intent.ShortcutIconResource
                        .fromContext(contxt, R.drawable.icon));
        installer.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        contxt.sendBroadcast(installer);
    }
判断快捷方式是否创建:
  1. private boolean isInstallShortcut() {  
  2.         boolean isInstallShortcut = false;  
  3.         final ContentResolver cr = MarketApplication  
  4.                 .getMarketApplicationContext().getContentResolver();  
  5.         String AUTHORITY = "com.android.launcher.settings";  
  6.         Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY  
  7.                 + "/favorites?notify=true");  
  8.   
  9.         Cursor c = cr.query(CONTENT_URI,  
  10.                 new String[] { "title""iconResource" }, "title=?",  
  11.                 new String[] { "名字" }, null);  
  12.         if (c != null && c.getCount() > 0) {  
  13.             isInstallShortcut = true;  
  14.         }  
  15.   
  16.         if (c != null) {  
  17.             c.close();  
  18.         }  
  19.   
  20.         if (isInstallShortcut) {  
  21.             return isInstallShortcut;  
  22.         }  
  23.   
  24.         AUTHORITY = "com.android.launcher2.settings";  
  25.         CONTENT_URI = Uri.parse("content://" + AUTHORITY  
  26.                 + "/favorites?notify=true");  
  27.         c = cr.query(CONTENT_URI, new String[] { "title""iconResource" },  
  28.                 "title=?"new String[] { "名字" }, null);  
  29.         if (c != null && c.getCount() > 0) {  
  30.             isInstallShortcut = true;  
  31.         }  
  32.   
  33.         if (c != null) {  
  34.             c.close();  
  35.         }  
  36.   
  37.         AUTHORITY = "com.baidu.launcher";  
  38.         CONTENT_URI = Uri.parse("content://" + AUTHORITY  
  39.                 + "/favorites?notify=true");  
  40.         c = cr.query(CONTENT_URI, new String[] { "title""iconResource" },  
  41.                 "title=?"new String[] { "名字" }, null);  
  42.         if (c != null && c.getCount() > 0) {  
  43.             isInstallShortcut = true;  
  44.         }  
  45.   
  46.         if (c != null) {  
  47.             c.close();  
  48.         }  
  49.   
  50.         return isInstallShortcut;  
  51.     }  
private boolean isInstallShortcut() {
        boolean isInstallShortcut = false;
        final ContentResolver cr = MarketApplication
                .getMarketApplicationContext().getContentResolver();
        String AUTHORITY = "com.android.launcher.settings";
        Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");

        Cursor c = cr.query(CONTENT_URI,
                new String[] { "title", "iconResource" }, "title=?",
                new String[] { "名字" }, null);
        if (c != null && c.getCount() > 0) {
            isInstallShortcut = true;
        }

        if (c != null) {
            c.close();
        }

        if (isInstallShortcut) {
            return isInstallShortcut;
        }

        AUTHORITY = "com.android.launcher2.settings";
        CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");
        c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" },
                "title=?", new String[] { "名字" }, null);
        if (c != null && c.getCount() > 0) {
            isInstallShortcut = true;
        }

        if (c != null) {
            c.close();
        }

        AUTHORITY = "com.baidu.launcher";
        CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");
        c = cr.query(CONTENT_URI, new String[] { "title", "iconResource" },
                "title=?", new String[] { "名字" }, null);
        if (c != null && c.getCount() > 0) {
            isInstallShortcut = true;
        }

        if (c != null) {
            c.close();
        }

        return isInstallShortcut;
    }
过滤特殊字符:
  1. private String StringFilter(String str) throws PatternSyntaxException {  
  2.     // 只允许字母和数字  
  3.     // String regEx = "[^a-zA-Z0-9]";  
  4.     // 清除掉所有特殊字符  
  5.     String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";  
  6.     Pattern p = Pattern.compile(regEx);  
  7.     Matcher m = p.matcher(str);  
  8.     return m.replaceAll("").trim();  
  9. }  
    private String StringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        // String regEx = "[^a-zA-Z0-9]";
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
执行shell语句:
  1. public int execRootCmdSilent(String cmd) {  
  2.     int result = -1;  
  3.     DataOutputStream dos = null;  
  4.   
  5.     try {  
  6.         Process p = Runtime.getRuntime().exec("su");  
  7.         dos = new DataOutputStream(p.getOutputStream());  
  8.         dos.writeBytes(cmd + "\n");  
  9.         dos.flush();  
  10.         dos.writeBytes("exit\n");  
  11.         dos.flush();  
  12.         p.waitFor();  
  13.         result = p.exitValue();  
  14.     } catch (Exception e) {  
  15.         e.printStackTrace();  
  16.     } finally {  
  17.         if (dos != null) {  
  18.             try {  
  19.                 dos.close();  
  20.             } catch (IOException e) {  
  21.                 e.printStackTrace();  
  22.             }  
  23.         }  
  24.     }  
  25.     return result;  
  26. }  
    public int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;

        try {
            Process p = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(p.getOutputStream());
            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            p.waitFor();
            result = p.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
获得文件MD5值:
  1. public String getFileMD5(File file) {  
  2.     if (!file.isFile()) {  
  3.         return null;  
  4.     }  
  5.   
  6.     MessageDigest digest = null;  
  7.     FileInputStream in = null;  
  8.     byte buffer[] = new byte[1024];  
  9.     int len;  
  10.     try {  
  11.         digest = MessageDigest.getInstance("MD5");  
  12.         in = new FileInputStream(file);  
  13.         while ((len = in.read(buffer, 01024)) != -1) {  
  14.             digest.update(buffer, 0, len);  
  15.         }  
  16.     } catch (Exception e) {  
  17.         e.printStackTrace();  
  18.         return null;  
  19.     } finally {  
  20.         if (in != null) {  
  21.             try {  
  22.                 in.close();  
  23.             } catch (IOException e) {  
  24.                 e.printStackTrace();  
  25.             }  
  26.         }  
  27.     }  
  28.     BigInteger bigInt = new BigInteger(1, digest.digest());  
  29.     return bigInt.toString(16);  
  30. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值