Android---常用代码片段整理
1最近有时间,整理了一下项目中常用到的代码
1、图片旋转:
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代码中设置
/** 全屏设置,隐藏窗口所有装饰 */
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
B、在AndroidManifest.xml中配置
<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如下:
Android:theme="@android:style/Theme.Dialog"
6、检查当前网络是否连上:
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 增加权限:
<uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE" />
7、检测某个Intent是否有效:
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 拨打电话:
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:
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中打开浏览器:**
Intent viewIntent = new
Intent("android.intent.action.VIEW",Uri.parse(
startActivity(viewIntent);
11、Android 获取设备唯一标识码:
String android_id = Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID);
12、Android中获取IP地址:
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中添加新的联系人:
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、查看电池使用情况:
Intent intentBatteryUsage = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
startActivity(intentBatteryUsage);
16、从res/raw打开文件
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 得到屏幕尺寸
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); //宽
int height = display.getHeight(); //高
18 关闭软键盘
private void hideSoftInput() {
InputMethodManager imm = (InputMethodManager) this
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
19 回退按钮
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
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/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 关闭游标和数据库
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加密
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、系统的版本信息
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地址和开机时间
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频率:
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
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) {
}
}
原文作者: slu128