Android之你不可不知道的小知識(shí)

打開軟件安裝頁(yè)面

一般下載完APK文件之后烹棉,都要打開軟件安裝頁(yè)面读慎,提示用戶進(jìn)行安裝怕品,可以用以下方法(固定寫法)

    Intent intent = new Intent();
    intent.setAction("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setDataAndType(Uri.fromFile(new File("apk在手機(jī)中的路徑/要安裝的軟件.apk")), "application/vnd.android.package-archive");
    startActivityForResult(intent, 0);      

分享軟件信息

如果想要分享軟件野舶,需要寫好預(yù)定要分享出去的信息易迹,可用以下方法:

    Intent intent = new Intent();
    intent.setAction("android.intent.action.SEND");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, "(自定義內(nèi)容)這是一個(gè)很牛逼的軟件,你信不信");
    startActivity(intent);

卸載軟件

卸載軟件一般都是使用Android內(nèi)置的卸載工具來(lái)卸載的平道,只需要傳入要卸載的軟件的包名睹欲,便可以打開其卸載頁(yè)面:

        Intent intent = new Intent();
        intent.setAction("android.intent.action.DELETE");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("package:" + "卸載軟件的包名"));
        startActivityForResult(intent, 0);

打開軟件詳情頁(yè)

此方法打開Android內(nèi)關(guān)于軟件的詳情頁(yè),需要傳入軟件報(bào)名

    Intent intent = new Intent();
    intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
    intent.setData(Uri.parse("package:" + "要打開軟件的包名"));
    startActivity(intent);

打開其他軟件

在自己的app中打開其他應(yīng)用可以使用這個(gè)方法

    PackageManager manager = getPackageManager();
    Intent launchIntentForPackage = manager.getLaunchIntentForPackage("要打開軟件的包名");
    if (launchIntentForPackage != null) {
        startActivity(launchIntentForPackage);
    }

跳轉(zhuǎn)到從應(yīng)用直接跳轉(zhuǎn)到主界面的方法

        //跳轉(zhuǎn)到主界面
        Intent intent = new Intent();
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.HOME");
        startActivity(intent);

跳轉(zhuǎn)到 web 頁(yè)面

        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://www.baidu.com");            //要跳轉(zhuǎn)的網(wǎng)頁(yè)
        intent.setData(content_url);
        startActivity(intent);

注冊(cè)開屏鎖屏的廣播接收者

注冊(cè)開屏鎖屏的廣播的IntentFliter所要添加的action是

    Intent.ACTION_SCREEN_OFF // 鎖屏?xí)r添加
    Intent.ACTION_SCREEN_ON  // 開屏是添加

獲取app信息的方法

獲取app信息(報(bào)名一屋、版本名墩虹、應(yīng)用圖標(biāo)薛窥、應(yīng)用名稱、是用戶程序還是系統(tǒng)程序、安裝在SD卡中還是手機(jī)內(nèi)存中)

    public class AppEnging {
public static List<AppInfo> getAppInfos(Context context){
    List<AppInfo> list = new ArrayList<AppInfo>();
    //獲取應(yīng)用程序信息
    //包的管理者
    PackageManager pm = context.getPackageManager();
    //獲取系統(tǒng)中安裝到所有軟件信息
    List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
    for (PackageInfo packageInfo : installedPackages) {
        //獲取包名
        String packageName = packageInfo.packageName;
        //獲取版本號(hào)
        String versionName = packageInfo.versionName;
        //獲取application
        ApplicationInfo applicationInfo = packageInfo.applicationInfo;
        int uid = applicationInfo.uid;
        //獲取應(yīng)用程序的圖標(biāo)
        Drawable icon = applicationInfo.loadIcon(pm);
        //獲取應(yīng)用程序的名稱
        String name = applicationInfo.loadLabel(pm).toString();
        //是否是用戶程序
        //獲取應(yīng)用程序中相關(guān)信息,是否是系統(tǒng)程序和是否安裝到SD卡
        boolean isUser;
        int flags = applicationInfo.flags;
        if ((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {
            //系統(tǒng)程序
            isUser = false;
        }else{
            //用戶程序
            isUser = true;
        }
        //是否安裝到SD卡
        boolean isSD;
        if ((applicationInfo.FLAG_EXTERNAL_STORAGE & flags) == applicationInfo.FLAG_EXTERNAL_STORAGE) {
            //安裝到了SD卡
            isSD = true;
        }else{
            //安裝到手機(jī)中
            isSD = false;
        }
        //添加到bean中
        AppInfo appInfo = new AppInfo(name, icon, packageName, versionName, isSD, isUser);
        //將bean存放到list集合
        list.add(appInfo);
    }
    return list;
}

}

// 封裝軟件信息的bean類
class AppInfo {
    //名稱
    private String name;
    //圖標(biāo)
    private Drawable icon;
    //包名
    private String packagName;
    //版本號(hào)
    private String versionName;
    //是否安裝到SD卡
    private boolean isSD;
    //是否是用戶程序
    private boolean isUser;

    public AppInfo() {
        super();
    }
    public AppInfo(String name, Drawable icon, String packagName,
            String versionName, boolean isSD, boolean isUser) {
        super();
        this.name = name;
        this.icon = icon;
        this.packagName = packagName;
        this.versionName = versionName;
        this.isSD = isSD;
        this.isUser = isUser;
    }
}

獲取系統(tǒng)中所有進(jìn)程信息的方法

        public class TaskEnging {
                /**
                    * 獲取系統(tǒng)中所有進(jìn)程信息
                    * @return
                    */
                public static List<TaskInfo> getTaskAllInfo(Context context){
                        List<TaskInfo> list = new ArrayList<TaskInfo>();
                        //1.進(jìn)程的管理者
                        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                        PackageManager pm = context.getPackageManager();
                        //2.獲取所有正在運(yùn)行的進(jìn)程信息
                        List<RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
                        //遍歷集合
                        for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
                            TaskInfo taskInfo = new TaskInfo();
                                //3.獲取相應(yīng)的信息
                                //獲取進(jìn)程的名稱,獲取包名
                                String packagName = runningAppProcessInfo.processName;
                                taskInfo.setPackageName(packagName);
                                //獲取進(jìn)程所占的內(nèi)存空間,int[] pids : 輸入幾個(gè)進(jìn)程的pid,就會(huì)返回幾個(gè)進(jìn)程所占的空間
                                MemoryInfo[] memoryInfo = activityManager.getProcessMemoryInfo(new int[]{runningAppProcessInfo.pid});
                                int totalPss = memoryInfo[0].getTotalPss();
                                long ramSize = totalPss*1024;
                                taskInfo.setRamSize(ramSize);
            try {
                //獲取application信息
                //packageName : 包名     flags:指定信息標(biāo)簽
                ApplicationInfo applicationInfo = pm.getApplicationInfo(packagName, 0);
                //獲取圖標(biāo)
                Drawable icon = applicationInfo.loadIcon(pm);
                taskInfo.setIcon(icon);
                //獲取名稱
                String name = applicationInfo.loadLabel(pm).toString();
                taskInfo.setName(name);
                //獲取程序的所有標(biāo)簽信息,是否是系統(tǒng)程序是以標(biāo)簽的形式展示
                int flags = applicationInfo.flags;
                boolean isUser;
                //判斷是否是用戶程序
                if ((applicationInfo.FLAG_SYSTEM & flags) == applicationInfo.FLAG_SYSTEM) {
                    //系統(tǒng)程序
                    isUser = false;
                    }else{
                        //用戶程序
                        isUser = true;
                    }
                    //保存信息
                    taskInfo.setUser(isUser);
                    } catch (NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    //taskinfo添加到集合
                    list.add(taskInfo);
                }
        return list;
    }

}


class TaskInfo {

    //名稱
    private String name;
    //圖標(biāo)
    private Drawable icon;
    //占用的內(nèi)存空間
    private long ramSize;
    //包名
    private String packageName;
    //是否是用戶程序
    private boolean isUser;
    //checkbox是否被選中
    private boolean isChecked = false;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Drawable getIcon() {
        return icon;
    }
    public void setIcon(Drawable icon) {
        this.icon = icon;
    }
    public long getRamSize() {
        return ramSize;
    }
    public void setRamSize(long ramSize) {
        this.ramSize = ramSize;
    }
    public String getPackageName() {
        return packageName;
    }
    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }
    public boolean isUser() {
        return isUser;
    }
    public void setUser(boolean isUser) {
        this.isUser = isUser;
    }
    public TaskInfo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public TaskInfo(String name, Drawable icon, long ramSize,
            String packageName, boolean isUser) {
                super();
                this.name = name;
                this.icon = icon;
                this.ramSize = ramSize;
                this.packageName = packageName;
                this.isUser = isUser;
            }
    @Override
    public String toString() {
        return "TaskInfo [name=" + name + ", icon=" + icon + ", ramSize="
                + ramSize + ", packageName=" + packageName + ", isUser="
                + isUser + "]";
            }
            public boolean isChecked() {
                return isChecked;
            }
            public void setChecked(boolean isChecked) {
                this.isChecked = isChecked;
            }
        }

清理所有空進(jìn)程的方法

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    //獲取正在運(yùn)行進(jìn)程
    List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
    for (RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
        //判斷我們的應(yīng)用進(jìn)程不能被清理
        if (!runningAppProcessInfo.processName.equals(getPackageName())) {
            am.killBackgroundProcesses(runningAppProcessInfo.processName);
        }
    }

動(dòng)態(tài)獲取服務(wù)是否開啟的方法

查看服務(wù)是否在后臺(tái)開啟排作,當(dāng)用戶直接停止服務(wù)的時(shí)候也能夠檢測(cè)得到

public static boolean isRunningService(String className,Context context){
    //進(jìn)程的管理者,活動(dòng)的管理者
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    //獲取正在運(yùn)行的服務(wù)
    List<RunningServiceInfo> runningServices = activityManager.getRunningServices(1000);//maxNum 返回正在運(yùn)行的服務(wù)的上限個(gè)數(shù),最多返回多少個(gè)服務(wù)
    //遍歷集合
    for (RunningServiceInfo runningServiceInfo : runningServices) {
        //獲取控件的標(biāo)示
        ComponentName service = runningServiceInfo.service;
        //獲取正在運(yùn)行的服務(wù)的全類名
        String className2 = service.getClassName();
        //將獲取到的正在運(yùn)行的服務(wù)的全類名和傳遞過(guò)來(lái)的服務(wù)的全類名比較,一直表示服務(wù)正在運(yùn)行  返回true,不一致表示服務(wù)沒有運(yùn)行  返回false
        if (className.equals(className2)) {
            return true;
        }
    }
    return false;
}

獲取內(nèi)存卡和SD卡可用空間的方法

/**
  * 獲取SD卡可用空間
  */
public static long getAvailableSD(){
    //獲取SD卡路徑
    File path = Environment.getExternalStorageDirectory();
    //硬盤的API操作
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();//獲取每塊的大小
            long totalBlocks = stat.getBlockCount();//獲取總塊數(shù)
            long availableBlocks = stat.getAvailableBlocks();//獲取可用的塊數(shù)
            return availableBlocks*blockSize;
        }
        /**
    *獲取內(nèi)存可用空間
    * @return
    */
    public static long getAvailableROM(){
        //獲取內(nèi)存路徑
        File path = Environment.getDataDirectory();
        //硬盤的API操作
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();//獲取每塊的大小
            long totalBlocks = stat.getBlockCount();//獲取總塊數(shù)
            long availableBlocks = stat.getAvailableBlocks();//獲取可用的塊數(shù)
            return availableBlocks*blockSize;
        }

簡(jiǎn)單的MD5加密

進(jìn)行簡(jiǎn)單的MD5加密妨马,傳入一個(gè)String进每,輸出經(jīng)過(guò)MD5加密后的密碼

    public static String passwordMD5(String password){
            StringBuilder sb = new StringBuilder();
            try {
                //1.獲取數(shù)據(jù)摘要器
                //arg0 : 加密的方式
                MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                //2.將一個(gè)byte數(shù)組進(jìn)行加密,返回的是一個(gè)加密過(guò)的byte數(shù)組,二進(jìn)制的哈希計(jì)算,md5加密的第一步
                byte[] digest = messageDigest.digest(password.getBytes());
                //3.遍歷byte數(shù)組
                for (int i = 0; i < digest.length; i++) {
                    //4.MD5加密
                    //byte值    -128-127
                    int result = digest[i] & 0xff;
                    //將得到int類型轉(zhuǎn)化成16進(jìn)制字符串
                    //String hexString = Integer.toHexString(result)+1;//不規(guī)則加密,加鹽
                    String hexString = Integer.toHexString(result);
                    if (hexString.length() < 2) {
                        //                  System.out.print("0");
                        sb.append("0");
                    }
                    //System.out.println(hexString);
                    //e10adc3949ba59abbe56e057f20f883e
                    sb.append(hexString);
                }
                return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        //找不到加密方式的異常
        e.printStackTrace();
    }
    return null;
}           

獲取剩余內(nèi)存和總內(nèi)存的方法

        /**
        * 獲取剩余內(nèi)存
        * @return
        */
    public static long getAvailableRam(Context context){
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //獲取內(nèi)存的信息,保存到memoryinfo中
        MemoryInfo outInfo = new MemoryInfo();
        am.getMemoryInfo(outInfo);
        //獲取空閑的內(nèi)存
        //outInfo.availMem;
        //      //獲取總的內(nèi)存
        //      outInfo.totalMem;
        return outInfo.availMem;
    }

    /**
        * 獲取總的內(nèi)存
        * @return
        * @deprecated
        */
public static long getTotalRam(Context context){
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    //獲取內(nèi)存的信息,保存到memoryinfo中
    MemoryInfo outInfo = new MemoryInfo();
    am.getMemoryInfo(outInfo);
    //獲取空閑的內(nèi)存
    //outInfo.availMem;
    //      //獲取總的內(nèi)存
    //      outInfo.totalMem;
    return outInfo.totalMem;//16版本之上才有,之下是沒有的
}

dp與px之間的簡(jiǎn)單轉(zhuǎn)換

/**
    * 根據(jù)手機(jī)的分辨率從 dip 的單位 轉(zhuǎn)成為 px(像素)
    * @return
    */  
public static int dip2qx(Context context, float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  //獲取屏幕的密度
        return (int) (dpValue * scale + 0.5f); //+0.5f四舍五入   3.7  3   3.7+0.5 = 4.2   4
    }  

    /**
    * 根據(jù)手機(jī)的分辨率從 px(像素) 的單位 轉(zhuǎn)成為 dp
    */  
public static int px2dip(Context context, float pxValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  

獲得系統(tǒng)聯(lián)系人的方法

public static List<HashMap<String, String>> getAllContactInfo(Context context) {
        SystemClock.sleep(3000);
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        // 1.獲取內(nèi)容解析者
        ContentResolver resolver = context.getContentResolver();
        // 2.獲取內(nèi)容提供者的地址:com.android.contacts
        // raw_contacts表的地址 :raw_contacts
        // view_data表的地址 : data
        // 3.生成查詢地址
        Uri raw_uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri date_uri = Uri.parse("content://com.android.contacts/data");
        // 4.查詢操作,先查詢r(jià)aw_contacts,查詢contact_id
        // projection : 查詢的字段
        Cursor cursor = resolver.query(raw_uri, new String[] { "contact_id" },
        null, null, null);
        // 5.解析cursor
        while (cursor.moveToNext()) {
            // 6.獲取查詢的數(shù)據(jù)
            String contact_id = cursor.getString(0);
            // cursor.getString(cursor.getColumnIndex("contact_id"));//getColumnIndex
            // : 查詢字段在cursor中索引值,一般都是用在查詢字段比較多的時(shí)候
            // 判斷contact_id是否為空
            if (!TextUtils.isEmpty(contact_id)) {//null   ""
            // 7.根據(jù)contact_id查詢view_data表中的數(shù)據(jù)
            // selection : 查詢條件
            // selectionArgs :查詢條件的參數(shù)
            // sortOrder : 排序
            // 空指針: 1.null.方法 2.參數(shù)為null
            Cursor c = resolver.query(date_uri, new String[] { "data1",
            "mimetype" }, "raw_contact_id=?",
            new String[] { contact_id }, null);
            HashMap<String, String> map = new HashMap<String, String>();
            // 8.解析c
            while (c.moveToNext()) {
                    // 9.獲取數(shù)據(jù)
                    String data1 = c.getString(0);
                    String mimetype = c.getString(1);
                    // 10.根據(jù)類型去判斷獲取的data1數(shù)據(jù)并保存
                    if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
                        // 電話
                        map.put("phone", data1);
                        } else if (mimetype.equals("vnd.android.cursor.item/name")) {
                            // 姓名
                            map.put("name", data1);
                        }
                    }
                    // 11.添加到集合中數(shù)據(jù)
                    list.add(map);
                    // 12.關(guān)閉cursor
                    c.close();
                }
            }
            // 12.關(guān)閉cursor
            cursor.close();
            return list;
        }

直接打開系統(tǒng)聯(lián)系人界面,并且獲取聯(lián)系人號(hào)碼的方法

使用startActivityForResult()開啟Activity弟翘,然后再onActivityResult()方法中獲取返回的聯(lián)系人號(hào)碼

// 在按鈕點(diǎn)擊事件中設(shè)置Intent,
Intent intent = new Intent();
intent.setAction("android.intent.action.PICK");
intent.addCategory("android.intent.category.DEFAULT");
intent.setType("vnd.android.cursor.dir/phone_v2");
startActivityForResult(intent, 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(data !=null){
        Uri uri = data.getData();
        String num = null;
        // 創(chuàng)建內(nèi)容解析者
                ContentResolver contentResolver = getContentResolver();
                Cursor cursor = contentResolver.query(uri,
                        null, null, null, null);
                        while(cursor.moveToNext()){
                            num = cursor.getString(cursor.getColumnIndex("data1"));                 
                        }
                        cursor.close();
                        num = num.replaceAll("-", "");//替換的操作,555-6 -> 5556
                    }
                }

獲取短信并保存到XML文件中的方法(備份短信)

獲取手機(jī)中的短信信息骄酗,并保存為XML文件稀余,路徑為:/mnt/sdcard/backupsms.xml

/**
 * 獲取短信
 */
public static void getAllSMS(Context context){
    //1.獲取短信
    //1.1獲取內(nèi)容解析者
    ContentResolver resolver = context.getContentResolver();
    //1.2獲取內(nèi)容提供者地址   sms,sms表的地址:null  不寫
    //1.3獲取查詢路徑
    Uri uri = Uri.parse("content://sms");
    //1.4.查詢操作
    //projection : 查詢的字段
    //selection : 查詢的條件
    //selectionArgs : 查詢條件的參數(shù)
    //sortOrder : 排序
    Cursor cursor = resolver.query(uri, new String[]{"address","date","type","body"}, null, null, null);
    //設(shè)置最大進(jìn)度
    int count = cursor.getCount();//獲取短信的個(gè)數(shù)


    //2.備份短信
    //2.1獲取xml序列器
    XmlSerializer xmlSerializer = Xml.newSerializer();
    try {
        //2.2設(shè)置xml文件保存的路徑
        //os : 保存的位置
        //encoding : 編碼格式
        xmlSerializer.setOutput(new FileOutputStream(new File("/mnt/sdcard/backupsms.xml")), "utf-8");
        //2.3設(shè)置頭信息
        //standalone : 是否獨(dú)立保存
        xmlSerializer.startDocument("utf-8", true);
        //2.4設(shè)置根標(biāo)簽
        xmlSerializer.startTag(null, "smss");
        //1.5.解析cursor
        while(cursor.moveToNext()){
            SystemClock.sleep(1000);
            //2.5設(shè)置短信的標(biāo)簽
            xmlSerializer.startTag(null, "sms");
            //2.6設(shè)置文本內(nèi)容的標(biāo)簽
            xmlSerializer.startTag(null, "address");
            String address = cursor.getString(0);
            //2.7設(shè)置文本內(nèi)容
            xmlSerializer.text(address);
            xmlSerializer.endTag(null, "address");

            xmlSerializer.startTag(null, "date");
            String date = cursor.getString(1);
            xmlSerializer.text(date);
            xmlSerializer.endTag(null, "date");

            xmlSerializer.startTag(null, "type");
            String type = cursor.getString(2);
            xmlSerializer.text(type);
            xmlSerializer.endTag(null, "type");

            xmlSerializer.startTag(null, "body");
            String body = cursor.getString(3);
            xmlSerializer.text(body);
            xmlSerializer.endTag(null, "body");

            xmlSerializer.endTag(null, "sms");
            System.out.println("address:"+address+"   date:"+date+"  type:"+type+"  body:"+body);

        }
        xmlSerializer.endTag(null, "smss");
        xmlSerializer.endDocument();
        //2.8將數(shù)據(jù)刷新到文件中
        xmlSerializer.flush();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

獲取手機(jī)屏幕高度和寬度的方法

        // 獲取屏幕的寬度
        WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
            // windowManager.getDefaultDisplay().getWidth();
        DisplayMetrics outMetrics = new DisplayMetrics();// 創(chuàng)建了一張白紙
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 給白紙?jiān)O(shè)置寬高
        width = outMetrics.widthPixels;
        height = outMetrics.heightPixels;

判斷網(wǎng)絡(luò)活動(dòng)狀態(tài)

public static boolean isNetworkConnected(Context context) {
    if (context != null) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
    }
    return false;
}

將圖片壓縮為指定尺寸

/第一種方法使用Bitmap加Matrix來(lái)縮放
public static Drawable resizeImage(Bitmap bitmap, int w, int h) 
{  
    Bitmap BitmapOrg = bitmap;  
    int width = BitmapOrg.getWidth();  
    int height = BitmapOrg.getHeight();  
    int newWidth = w;  
    int newHeight = h;  

    float scaleWidth = ((float) newWidth) / width;  
    float scaleHeight = ((float) newHeight) / height;  

    Matrix matrix = new Matrix();  
    matrix.postScale(scaleWidth, scaleHeight);  
    // if you want to rotate the Bitmap   
    // matrix.postRotate(45);   
    Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,  
                    height, matrix, true);  
    return new BitmapDrawable(resizedBitmap);  
}

//第二種方法使用BitmapFactory.Options的inSampleSize參數(shù)來(lái)縮放
public static Drawable resizeImage2(String path,
        int width,int height) 
{
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;//不加載bitmap到內(nèi)存中
    BitmapFactory.decodeFile(path,options); 
    int outWidth = options.outWidth;
    int outHeight = options.outHeight;
    options.inDither = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inSampleSize = 1;
     
    if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) 
    {
        int sampleSize=(outWidth/width+outHeight/height)/2;
        Log.d(tag, "sampleSize = " + sampleSize);
        options.inSampleSize = sampleSize;
    }
 
    options.inJustDecodeBounds = false;
    return new BitmapDrawable(BitmapFactory.decodeFile(path, options));     
}

WebView設(shè)置圖片適配

使用WebView的時(shí)候會(huì)出現(xiàn)加載出來(lái)的網(wǎng)頁(yè)內(nèi)容圖片過(guò)大的現(xiàn)象,解決這一問題的辦法很簡(jiǎn)單趋翻,就是在html的<img標(biāo)題中添加樣式睛琳,如下:

原始的圖片標(biāo)簽[圖片上傳失敗...(image-65a9ce-1510383740421)] 

修改之后的標(biāo)簽[圖片上傳失敗...(image-368061-1510383740421)] 

這一處理方法可通過(guò)服務(wù)端處理,也可通過(guò)客戶端處理踏烙。
通過(guò)客戶端處理則要先獲取到html頁(yè)面的選代碼师骗,然后通過(guò)字符串替換的方式進(jìn)行。
另一種是通過(guò)jsoup處理讨惩,代碼如下:

// 相關(guān)連接 http://blog.csdn.net/pengpenggxp/article/details/53289139
public static String getNewContent(String htmltext){

    Document doc= Jsoup.parse(htmltext);
    Elements elements=doc.getElementsByTag("img");
    for (Element element : elements) {
        element.attr("width","100%").attr("height","auto");
    }

    return doc.toString();
}

將數(shù)據(jù)加載到ListView的頂部

使用ListView下拉刷新的時(shí)候會(huì)有個(gè)問題辟癌,那就是如何將數(shù)據(jù)加載到頂部,代碼如下:

//myAdapter為自定義的Adapter
//list是List<String>集合
// 假設(shè)ListView已經(jīng)填充了myAdapter
            List<String> refreshList = new ArrayList<String>();
            for(int i = 0; i < 5; i ++){
                String str = "下拉更新的第" + i +"行數(shù)據(jù)";
                refreshList.add(str);
            }
            refreshList.addAll(list);
            list.removeAll(list);
            list.addAll(refreshList);
            myAdapter.notifyDataSetChanged();

設(shè)置一個(gè)臨時(shí)refreshList 變量步脓,然后將原本的list集合添加到臨時(shí)變量refreshList中愿待,達(dá)到將數(shù)據(jù)添加到新獲取的數(shù)據(jù)后面的效果浩螺。
然后list清空自己靴患,再添加refreshList到其中。

注銷靜態(tài)廣播

動(dòng)態(tài)廣播注銷很簡(jiǎn)單要出,只需要使用unregisterReceiver()就可以了鸳君,那么靜態(tài)廣播呢?
答案是使用
可以利用PackageManager中的setComponentEnableSetting()這個(gè)函數(shù)來(lái)解決這個(gè)問題患蹂,對(duì)于setComponetEnableSetting()這個(gè)函數(shù)或颊。

getPackageManager().setComponentEnabledSetting(  
            new ComponentName("com.example.broadcasttest",  
                    mStaBroadcastReceiver.class.getName()),  
            PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,  
            PackageManager.DONT_KILL_APP);//這個(gè)地方因?yàn)楫?dāng)你點(diǎn)擊按鈕使靜態(tài)注冊(cè)的廣播disabled之后,下次進(jìn)來(lái)的時(shí)候廣播就不能用了传于,相當(dāng)于已經(jīng)修改了Manifest了囱挑,這個(gè)地方還原成default,也就是之前在Manifest中設(shè)置的默認(rèn)值(enable="true")  
 }                                                                                              

意思簡(jiǎn)單來(lái)說(shuō)就是沼溜,能夠使四大組件從enable轉(zhuǎn)化為disabled平挑;
第一個(gè)參數(shù)是一個(gè)ComponentName()對(duì)象,指定你要設(shè)置的組件的名字和所在的報(bào)名系草;
第二個(gè)參數(shù)newState這個(gè)參數(shù)來(lái)決定如何轉(zhuǎn)換通熄;
第三個(gè)參數(shù)flags表示行為,有兩種不同的行為找都,如果設(shè)置為DONT_KILL_APP那么在調(diào)用PackageManager.setComponentEnableSetting()設(shè)置Manifest.xml的時(shí)候就不至于
殺死APP唇辨,反之就是0,這個(gè)時(shí)候你在設(shè)置就會(huì)出現(xiàn)閃退,因?yàn)檫@個(gè)時(shí)候已經(jīng)把APP殺死了能耻。

直接在在界面上繪制圖形

    ImageView imageView = new ImageView(this);
    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    Bitmap bmp = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bmp);
    Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setStyle(Paint.Style.STROKE);//不填充
    paint.setStrokeWidth(1);  //線的寬度
    Rect rect = new Rect(20, 20, 200, 200);
    canvas.drawRect(rect, paint);

    paint.setTextSize(20);//設(shè)置字體大小
    paint.setStyle(Paint.Style.FILL);//不填充
    paint.setTypeface(Typeface.DEFAULT_BOLD);//設(shè)置字體類型
    canvas.drawText("Hello, world", 30, 30, paint);

    canvas.drawBitmap(bmp, 0, 0, paint);
    imageView.setImageBitmap(bmp);
    addContentView(imageView, layoutParams);

可以在Activity中直接繪制一個(gè)圖片并且添加圖形赏枚、文字等等

參考鏈接:http://blog.csdn.net/rockcode_li/article/details/38457901

Android:橫屏?xí)r禁止輸入法全屏

方法一:在代碼里直接對(duì)EditText進(jìn)行設(shè)置

mEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);

方法二:在XML布局文件里的EditText加上屬性

android:imeOptions="flagNoExtractUi"

方法三:如果是使用自定義鍵盤的話亡驰,需要重寫onEvaluateFullscreenMode()返回值會(huì)false即可。

建議使用前兩種方法饿幅。

鏈接:http://www.reibang.com/p/9a81a34e64dc

gong 將 List 對(duì)象轉(zhuǎn)為 json

        /**
         * 把json 字符串轉(zhuǎn)化成list
         */
        public static <T> List<T> jsonToList(String json, Class<T> cls) {
            List<T> list = new ArrayList<>();
            try {
                Gson gson = new Gson();
                JsonArray array = new JsonParser().parse(json).getAsJsonArray();
                for (final JsonElement elem : array) {
                    list.add(gson.fromJson(elem, cls));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末隐解,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子诫睬,更是在濱河造成了極大的恐慌煞茫,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,682評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件摄凡,死亡現(xiàn)場(chǎng)離奇詭異续徽,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)亲澡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門钦扭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人床绪,你說(shuō)我怎么就攤上這事客情。” “怎么了癞己?”我有些...
    開封第一講書人閱讀 165,083評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵膀斋,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我痹雅,道長(zhǎng)仰担,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,763評(píng)論 1 295
  • 正文 為了忘掉前任绩社,我火速辦了婚禮摔蓝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘愉耙。我一直安慰自己贮尉,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,785評(píng)論 6 392
  • 文/花漫 我一把揭開白布朴沿。 她就那樣靜靜地躺著猜谚,像睡著了一般。 火紅的嫁衣襯著肌膚如雪悯仙。 梳的紋絲不亂的頭發(fā)上龄毡,一...
    開封第一講書人閱讀 51,624評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音锡垄,去河邊找鬼沦零。 笑死,一個(gè)胖子當(dāng)著我的面吹牛货岭,可吹牛的內(nèi)容都是我干的路操。 我是一名探鬼主播疾渴,決...
    沈念sama閱讀 40,358評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼屯仗!你這毒婦竟也來(lái)了搞坝?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,261評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤魁袜,失蹤者是張志新(化名)和其女友劉穎桩撮,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體峰弹,經(jīng)...
    沈念sama閱讀 45,722評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡店量,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鞠呈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片融师。...
    茶點(diǎn)故事閱讀 40,030評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖蚁吝,靈堂內(nèi)的尸體忽然破棺而出旱爆,到底是詐尸還是另有隱情,我是刑警寧澤窘茁,帶...
    沈念sama閱讀 35,737評(píng)論 5 346
  • 正文 年R本政府宣布怀伦,位于F島的核電站,受9級(jí)特大地震影響庙曙,放射性物質(zhì)發(fā)生泄漏空镜。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,360評(píng)論 3 330
  • 文/蒙蒙 一捌朴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧张抄,春花似錦砂蔽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至极谊,卻和暖如春诡右,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背轻猖。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工帆吻, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人咙边。 一個(gè)月前我還...
    沈念sama閱讀 48,237評(píng)論 3 371
  • 正文 我出身青樓猜煮,卻偏偏與公主長(zhǎng)得像次员,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子王带,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,976評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容