日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Android---常用代碼片段整理

 東茹閣 2013-07-01

作者:slu128更新于 05月02日訪問(100)評論(0

Android---常用代碼片段整理

1
 最近有時間,整理了一下項目中常用到的代碼

1、圖片旋轉(zhuǎn):

1
2
3
4
5
6
Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.moon);
Matrix matrix = new Matrix();
matrix.postRotate(-90);//旋轉(zhuǎn)的角度
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
                    bitmapOrg.getWidth(), bitmapOrg.getHeight(), matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

2、獲取手機號碼:
//創(chuàng)建電話管理

TelephonyManager tm = (TelephonyManager)

//與手機建立連接
activity.getSystemService(Context.TELEPHONY_SERVICE);

//獲取手機號碼

String phoneId = tm.getLine1Number();

//記得在manifest file中添加

//程序在模擬器上無法實現(xiàn),必須連接手機

3.格式化string.xml 中的字符串:
// in strings.xml..
Thanks for visiting %s. You age is %d!

// and in the java code:
String.format(getString(R.string.my_text), "oschina", 33);

4、Android設(shè)置全屏的方法:
A.在java代碼中設(shè)置
/** 全屏設(shè)置,隱藏窗口所有裝飾 */

1
2
3
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

B、在AndroidManifest.xml中配置

1
2
3
4
5
6
7
<activity android:name=".Login.NetEdit"  android:label="@string/label_net_Edit" 
            android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
<intent-filter>
  <action android:name="android.intent.Net_Edit" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>

5、設(shè)置Activity為Dialog的形式:
在AndroidManifest.xml中配置Activity節(jié)點是配置theme如下:

1
Android:theme="@android:style/Theme.Dialog"

6、檢查當(dāng)前網(wǎng)絡(luò)是否連上:

1
2
3
4
5
ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);  

boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); 

boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); 

在AndroidManifest.xml 增加權(quán)限:

1
<uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE" />

7、檢測某個Intent是否有效:

1
2
3
4
5
6
7
8
public static boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> list =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

8、android 撥打電話:

1
2
3
4
5
6
7
try {
   Intent intent = new Intent(Intent.ACTION_CALL);
   intent.setData(Uri.parse("tel:+110"));
   startActivity(intent);
} catch (Exception e) {
   Log.e("SampleApp", "Failed to invoke call", e);
}

9、android中發(fā)送Email:

1
2
3
4
5
6
7
Intent i = new Intent(Intent.ACTION_SEND);  
//i.setType("text/plain"); //模擬器請使用這行
i.setType("message/rfc822") ; // 真機上使用這行
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com","test@163.com});  
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");  
i.putExtra(Intent.EXTRA_TEXT,"body goes here");  
startActivity(Intent.createChooser(i, "Select email application."));

10、Android中打開瀏覽器:**

1
2
3
Intent viewIntent = new 
    Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com"));
startActivity(viewIntent);

11、Android 獲取設(shè)備唯一標(biāo)識碼:
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);

12、Android中獲取IP地址:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); 
  en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); 
  enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

13、android獲取存儲卡路徑以及使用情況:
/** 獲取存儲卡路徑 /
File sdcardDir=Environment.getExternalStorageDirectory();
/
* StatFs 看文件系統(tǒng)空間使用情況 /
StatFs statFs=new StatFs(sdcardDir.getPath());
/
* Block 的 size*/
Long blockSize=statFs.getBlockSize();
/** 總 Block 數(shù)量 /
Long totalBlocks=statFs.getBlockCount();
/
* 已使用的 Block 數(shù)量 */
Long availableBlocks=statFs.getAvailableBlocks();

14 android中添加新的聯(lián)系人:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private Uri insertContact(Context context, String name, String phone) {

       ContentValues values = new ContentValues();
       values.put(People.NAME, name);
       Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
       Uri numberUri = Uri.withAppendedPath(uri, People.Phones.CONTENT_DIRECTORY);
       values.clear();

       values.put(Contacts.Phones.TYPE, People.Phones.TYPE_MOBILE);
       values.put(People.NUMBER, phone);
       getContentResolver().insert(numberUri, values);

       return uri;
}

15、查看電池使用情況:

1
2
Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);        
startActivity(intentBatteryUsage);

16、從res/raw打開文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
  public static String openFileFromRaw(Context context) throws IOException {
        String content = "";
        InputStream inputStream = context.getResources().openRawResource(R.raw.provinces);

        if (inputStream != null) {
            BufferedReader buffreader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            //分行讀取
            try {
                while ((line = buffreader.readLine()) != null) {
                    content += line + "n";
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            inputStream.close();
        }

          return content   ;

    }

17 得到屏幕尺寸

1
2
3
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); //寬
int height = display.getHeight();  //高

18 關(guān)閉軟鍵盤

1
2
3
4
5
  private void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }

19 回退按鈕

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            new AlertDialog.Builder(activity_login.this)
                    .setTitle("退出系統(tǒng)")
                    .setMessage("確定要退出系統(tǒng)嗎")
                    .setPositiveButton("退出",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    finish();
                                }
                            })
                            // Leave
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.cancel();
                                }
                            }).show();
        }
        return false;
    }

20 btn_selector

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas./apk/res/android">
    <!-- pressed -->
    <item android:state_pressed="true" android:drawable="@drawable/btn_press"/>
    <!-- focused -->
    <item android:state_focused="true" android:drawable="@drawable/btn"/>
    <!-- default -->
    <item android:drawable="@drawable/btn"/>
</selector>

21 關(guān)閉游標(biāo)和數(shù)據(jù)庫

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
private void close(Cursor cursor, SQLiteDatabase database)
{
    try
  {
    if (cursor != null && !cursor.isClosed())                 
    {
        cursor.close();             
    }      
   }

    catch (Exception e)
               {}           
   try 
   {     
    dbHelper.closeDb(database);               
   }              
  catch (Exception e)
                {             
  }    
}

22 MD5加密

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString().toLowerCase();
    }

23、系統(tǒng)的版本信息

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public String[] getVersion(){  
    String[] version={"null","null","null","null"};  
    String str1 = "/proc/version";  
    String str2;  
    String[] arrayOfString;  
    try {  
        FileReader localFileReader = new FileReader(str1);  
        BufferedReader localBufferedReader = new BufferedReader(  
                localFileReader, 8192);  
        str2 = localBufferedReader.readLine();  
        arrayOfString = str2.split("\s+");  
        version[0]=arrayOfString[2];//KernelVersion  
        localBufferedReader.close();  
    } catch (IOException e) {  
    }  
    version[1] = Build.VERSION.RELEASE;// firmware version  
    version[2]=Build.MODEL;//model  
    version[3]=Build.DISPLAY;//system version  
    return version;  
} 

24、mac地址和開機時間

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public String[] getOtherInfo(){  
    String[] other={"null","null"};  
       WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);  
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
       if(wifiInfo.getMacAddress()!=null){  
        other[0]=wifiInfo.getMacAddress();  
    } else {  
        other[0] = "Fail";  
    }  
    other[1] = getTimes();  
       return other;  
}  
private String getTimes() {  
    long ut = SystemClock.elapsedRealtime() / 1000;  
    if (ut == 0) {  
        ut = 1;  
    }  
    int m = (int) ((ut / 60) % 60);  
    int h = (int) ((ut / 3600));  
    return h + " " + mContext.getString(R.string.info_times_hour) + m + " " 
            + mContext.getString(R.string.info_times_minute);  
} 

25、CPU頻率,CPU信息:/proc/cpuinfo和/proc/stat
通過讀取文件/proc/cpuinfo系統(tǒng)CPU的類型等多種信息。
讀取/proc/stat 所有CPU活動的信息來計算CPU使用率

下面我們就來講講如何通過代碼來獲取CPU頻率:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.orange.cpu;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class CpuManager {
  **   // 獲取CPU最大頻率(單位KHZ)
     // "/system/bin/cat" 命令行
     // "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" 存儲最大頻率的文件的路徑**
        public static String getMaxCpuFreq() {
                String result = "";
                ProcessBuilder cmd;
                try {
                        String[] args = { "/system/bin/cat",
                                        "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
                        cmd = new ProcessBuilder(args);
                        Process process = cmd.start();
                        InputStream in = process.getInputStream();
                        byte[] re = new byte[24];
                        while (in.read(re) != -1) {
                                result = result + new String(re);
                        }
                        in.close();
                } catch (IOException ex) {
                        ex.printStackTrace();
                        result = "N/A";
                }
                return result.trim();
        }

         **// 獲取CPU最小頻率(單位KHZ)**
        public static String getMinCpuFreq() {
                String result = "";
                ProcessBuilder cmd;
                try {
                        String[] args = { "/system/bin/cat",
                                        "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
                        cmd = new ProcessBuilder(args);
                        Process process = cmd.start();
                        InputStream in = process.getInputStream();
                        byte[] re = new byte[24];
                        while (in.read(re) != -1) {
                                result = result + new String(re);
                        }
                        in.close();
                } catch (IOException ex) {
                        ex.printStackTrace();
                        result = "N/A";
                }
                return result.trim();
        }

         **// 實時獲取CPU當(dāng)前頻率(單位KHZ)**
        public static String getCurCpuFreq() {
                String result = "N/A";
                try {
                        FileReader fr = new FileReader(
                                        "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
                        BufferedReader br = new BufferedReader(fr);
                        String text = br.readLine();
                        result = text.trim();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                return result;
        }

       ** // 獲取CPU名字**
        public static String getCpuName() {
                try {
                        FileReader fr = new FileReader("/proc/cpuinfo");
                        BufferedReader br = new BufferedReader(fr);
                        String text = br.readLine();
                        String[] array = text.split(":\s+", 2);
                        for (int i = 0; i < array.length; i++) {
                        }
                        return array[1];
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                return null;
        }
}

26、內(nèi)存:/proc/meminfo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public void getTotalMemory() {  
        String str1 = "/proc/meminfo";  
        String str2="";  
        try {  
            FileReader fr = new FileReader(str1);  
            BufferedReader localBufferedReader = new BufferedReader(fr, 8192);  
            while ((str2 = localBufferedReader.readLine()) != null) {  
                Log.i(TAG, "---" + str2);  
            }  
        } catch (IOException e) {  
        }  
    } 

聲明:eoe文章著作權(quán)屬于作者,受法律保護,轉(zhuǎn)載時請務(wù)必以超鏈接形式附帶如下信息

原文作者: slu128

原文地址: http://my./loody128/archive/3244.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多