分享

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

 东茹阁 2013-07-01

作者:slu128更新于 05月02日访问(100)评论(0

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

1
 最近有时间,整理了一下项目中常用到的代码

1、图片旋转:

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

2、获取手机号码:
//创建电话管理

TelephonyManager tm = (TelephonyManager)

//与手机建立连接
activity.getSystemService(Context.TELEPHONY_SERVICE);

//获取手机号码

String phoneId = tm.getLine1Number();

//记得在manifest file中添加

//程序在模拟器上无法实现,必须连接手机

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设置全屏的方法:
A.在java代码中设置
/** 全屏设置,隐藏窗口所有装饰 */

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、设置Activity为Dialog的形式:
在AndroidManifest.xml中配置Activity节点是配置theme如下:

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

6、检查当前网络是否连上:

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 增加权限:

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中发送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 获取设备唯一标识码:
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 看文件系统空间使用情况 /
StatFs statFs=new StatFs(sdcardDir.getPath());
/
* Block 的 size*/
Long blockSize=statFs.getBlockSize();
/** 总 Block 数量 /
Long totalBlocks=statFs.getBlockCount();
/
* 已使用的 Block 数量 */
Long availableBlocks=statFs.getAvailableBlocks();

14 android中添加新的联系人:

 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 关闭软键盘

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("退出系统")
                    .setMessage("确定要退出系统吗")
                    .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 关闭游标和数据库

 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、系统的版本信息

 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系统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当前频率(单位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、内存:/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文章著作权属于作者,受法律保护,转载时请务必以超链接形式附带如下信息

原文作者: slu128

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多