Android 開發中的一些小技巧

m8x2 9年前發布 | 3K 次閱讀 Java Android

dip轉px

    public int convertDipOrPx(int dip) {
        float scale = MarketApplication.getMarketApplicationContext()
                .getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

獲取當前窗體,并添加自定義view:

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圖片樣式:

        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);
        }

=網絡==================================

判斷網絡是否可用:

/**

 * 網絡是否可用
 * 
 * @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;
}</pre> 

方法二:

    /*

 * 判斷網絡連接是否已開 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;
}</pre> 

判斷是不是Wifi連接:

    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;
    }

判斷當前網絡類型

/**

 * 網絡方式檢查
 */
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;
    }
}</pre> 



</div>

獲取下載文件的真實名字

    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;
}</pre> 

=圖片==========================

bitmap轉Byte數組(微信分享就需要用到)

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;
}</pre> Resources轉Bitmap 

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);
}</pre> 保存圖片到SD卡 

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();
        }
    }
}</pre> 

=系統==============================

根據包名打開一個應用程序

    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;
}</pre> 

判斷是否APK是否安裝過

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

    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

    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卡是否可用

    public boolean CheckSD() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

創建快捷方式:

    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);
}</pre> 

判斷快捷方式是否創建:

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;
}</pre> 

過濾特殊字符:

    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語句:

    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;
}</pre> 

獲得文件MD5值:

    public String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }

    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
        digest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    BigInteger bigInt = new BigInteger(1, digest.digest());
    return bigInt.toString(16);
}</pre> 轉自:http://blog.csdn.net/h3c4lenovo/article/details/16879435
 本文由用戶 m8x2 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!