把自己收集的以及常用的代码块及工具类发送给大家,有需要的直接拷走哦,方便你我他,有错误请指出。
dp和px之间转换
public class DensityUtil {
/**
* 根据手机的分辨率从 dip 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}
根据uri获取真实路径
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
横竖屏切换
< activity android:name="MyActivity"
android:configChanges="orientation|keyboardHidden"> //Activity需要设置的
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//加入横屏要处理的代码
}else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
//加入竖屏要处理的代码
}
}
获取mac地址
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>//需要添加权限
private String getLocalMacAddress() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}
获取sd卡状态
/** 获取存储卡路径 */
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();
获取标题栏状态栏高度
/**
Android获取状态栏和标题栏的高度
1.Android获取状态栏高度:
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
2.获取标题栏高度:
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
**/
//例子代码:
package com.cn.lhq;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
public class Main extends Activity {
ImageView iv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) this.findViewById(R.id.ImageView01);
iv.post(new Runnable() {
public void run() {
viewInited();
}
});
Log.v("test", "== ok ==");
}
private void viewInited() {
Rect rect = new Rect();
Window window = getWindow();
iv.getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
.getTop();
int titleBarHeight = contentViewTop - statusBarHeight;
// 测试结果:ok之后 100多 ms 才运行了
Log.v("test", "=-init-= statusBarHeight=" + statusBarHeight
+ " contentViewTop=" + contentViewTop + " titleBarHeight="
+ titleBarHeight);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
获取各种窗体高度
//取得窗口属性
getWindowManager().getDefaultDisplay().getMetrics(dm);
//窗口的宽度
int screenWidth = dm.widthPixels;
//窗口高度
int screenHeight = dm.heightPixels;
textView = (TextView)findViewById(R.id.textView01);
textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight);
/**获取状态栏高度
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个
getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
view plain**/
Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
/**获取标题栏高度
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包
括标题栏的部分,然后就可以知道标题栏的高度了。
view plain**/
int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
禁用home键盘
/** 问题的提出
Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办?
问题的解决
先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者随你XXOO。
**/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if(KeyEvent.KEYCODE_HOME==keyCode)
android.os.Process.killProcess(android.os.Process.myPid());
return super.onKeyDown(keyCode, event);
}
@Override
public void onAttachedToWindow(){
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
//加权限禁止Home键
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
开机启动
public class StartupReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startupintent = new Intent(context,StrongTracks.class);
startupintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupintent);
}
}
//清单文件中添加
<receiver
android:name=".StartupReceiver">
<intent-filter>
<!-- 系统启动完成后会调用 -->
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
控制对话框位置
Window window =dialog.getWindow();// 得到对话框的窗口.
WindowManager.LayoutParams wl = window.getAttributes();
wl.x = x;//这两句设置了对话框的位置.0为中间
wl.y =y;
wl.width =w;
wl.height =h;
wl.alpha =0.6f;// 这句设置了对话框的透明度
挪动dialog的位置
Window mWindow = dialog.getWindow();
WindowManager.LayoutParams lp = mWindow.getAttributes();
lp.x = 10; //新位置X坐标
lp.y = -100; //新位置Y坐标
dialog.onWindowAttributesChanged(lp);
判断网络状态
//清单文件中配置
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
//代码
private boolean getNetWorkStatus() {
boolean netSataus = false;
ConnectivityManager cwjManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() != null) {
netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
}
if (!netSataus) {
Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络")
.setMessage("是否对网络进行设置?");
b.setPositiveButton("是", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent mIntent = new Intent("/");
ComponentName comp = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction("android.intent.action.VIEW");
startActivityForResult(mIntent,0);
}
}).setNeutralButton("否", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
}).show();
}
设置apn
ContentValues values = new ContentValues();
values.put(NAME, "CMCC cmwap");
values.put(APN, "cmwap");
values.put(PROXY, "10.0.0.172");
values.put(PORT, "80");
values.put(MMSPROXY, "");
values.put(MMSPORT, "");
values.put(USER, "");
values.put(SERVER, "");
values.put(PASSWORD, "");
values.put(MMSC, "");
values.put(TYPE, "");
values.put(MCC, "460");
values.put(MNC, "00");
values.put(NUMERIC, "46000");
reURI = getContentResolver().insert(Uri.parse("content://telephony/carriers"), values);
//首选接入点"content://telephony/carriers/preferapn"
调节屏幕亮度
public void setBrightness(int level) {
ContentResolver cr = getContentResolver();
Settings.System.putInt(cr, "screen_brightness", level);
Window window = getWindow();
LayoutParams attributes = window.getAttributes();
float flevel = level;
attributes.screenBrightness = flevel / 255;
getWindow().setAttributes(attributes);
}
显示及隐藏软键盘
//隐藏软键盘
((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//显示软键盘,控件ID可以是EditText,TextView
((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(控件ID, 0);
BitMap、Drawable、inputStream及byte[] 互转
//(1) BitMap to inputStream:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream isBm = new ByteArrayInputStream(baos .toByteArray());
// (2)BitMap to byte[]:
Bitmap defaultIcon = BitmapFactory.decodeStream(in);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
// (3)Drawable to byte[]:
Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap);
byte[] bitmapdata = stream.toByteArray();
//(4)byte[] to Bitmap :
Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);
LogUtil
/**
* 日志工具类
*
* @author wangdh 1. 上线之后,可以统一屏蔽 2. 团队开发,区分个人log
*/
public class LogUtil {
private static boolean isDubug = false;// 是否是调试(开发)阶段
public static void logZhang(String msg) {
if (isDubug)
Log.i("zhang", msg);
}
public static void logLi(String msg) {
if (isDubug)
Log.i("li", msg);
}
}
md5加密
public class MD5Utils {
//来点佐料
private static String SALT = "asdjh@@^*%%jhsha~";
/**
* 原来密码和佐料混合然后MD5加密
* @param password
* @return
*/
public static String encrypt(String password) {
//初始化一个加密密码
String encryptPassword = null;
//MD5加密
try {
String msg = SALT+password+SALT;
StringBuilder sb = new StringBuilder();
MessageDigest md5 = MessageDigest.getInstance("md5");
byte[] encryptBytes = md5.digest(msg.getBytes());
for(byte b:encryptBytes){
//变换成绝对值
int i = b&0xFF;
//把小于255的数转换成16进制的字符串
String hexString = Integer.toHexString(i);
//长度等于1补0
if(hexString.length()==1){
hexString = "0"+hexString;
}
sb.append(hexString);
}
encryptPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptPassword;
}
}
时间转换工具
public class StringUtils {
private static final int HOUR = 1000*60*60;
private static final int MIN = 1000*60;
private static final int SEC = 1000;
/**
* 时间格式化
* 00:00:00
* 00:00
*/
public static String formatTime(int time){
//小时
int hour = time/HOUR;
//分钟
int min = time%HOUR/MIN;
//秒
int sec = time%MIN/SEC;
if(hour==0){
// 00:00 (%占位符,02 :两位数字,如果不满两位自动补零)
return String.format("%02d:%02d", min,sec);
}else{
return String.format("%02d:%02d:%02d",hour, min,sec);
}
}
/**
* 获取格式系统时间
*/
public static String getFormaterSystemTime(){
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");//hh:12,HH:24
return format.format(new Date());//System.currentTimeMillis()
}
}
版本号相关
public class APPUtils {
/**
* 获取版本号
*
* @param context
* @return 返回版本号
*/
public static int getVersionCode(Context context) {
int versionCode = 0;
// 获取包的管理
PackageManager packageManager = context.getPackageManager();
try {
// 拿到包的所有信息
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
// 获取本号并返回
versionCode = packageInfo.versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionCode;
}
/**
* 获取版本名字
*
* @param context
* @return 返回版本名字
*/
public static String getVersionName(Context context) {
String versionName = null;
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
versionName = packageInfo.versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return versionName;
}
public static void showToast(final Activity activity,final String string){
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, string, 0).show();
}
});
}
/**
* 判断SD卡的状态
* @return 挂载则返回true,否则返回flast
*/
public static boolean getSdState(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
}
进程相关
public class TaskUtils {
/**
* 获得运行中的进程个数
* @param act
* @return
*/
public static int getRunnintProcCount(Context act) {
ActivityManager am = (ActivityManager)act. getSystemService(Context.ACTIVITY_SERVICE);
// 运行中进程的个数
return am.getRunningAppProcesses().size();
}
/**
* 获得可用内存大小
* @param act
* @return
*/
public static long getAvailMem(Context act) {
ActivityManager am = (ActivityManager)act. getSystemService(Context.ACTIVITY_SERVICE);
MemoryInfo outInfo = new MemoryInfo();
am.getMemoryInfo(outInfo);
return outInfo.availMem; // 可用内存
}
/**
* 获得总的内存大小
* @return
* byte
*/
public static long getTotalMem() {
// 读取 /proc/meminfo 文件,其中,第一行,就是 内存的总量信息
try {
String path = "/proc/meminfo";
FileInputStream fin = new FileInputStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
String line = reader.readLine(); // MemTotal: 513744 kB
StringBuffer sb = new StringBuffer();
for(int i=0;i<line.length();i++){
char c = line.charAt(i);// 获得指定下标的字符
// 判断字符是否是数字
if( c >='0' && c<='9'){
sb.append(c);
}
}
return Long.parseLong(sb.toString())*1024;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 获得所有的正在运行的进程信息
* @param ctx
* @return
*/
public static List<TaskInfoBean> getAllRunningTaskInfo(Context ctx){
List<TaskInfoBean> allTaskList = new ArrayList<TaskInfoBean>();
ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
PackageManager pm = ctx.getPackageManager(); // project Manager 项目经理
List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();
for (RunningAppProcessInfo appProcessInfo : runningAppProcesses) {
// appProcessInfo.lru; LRU less recent use
TaskInfoBean taskInfo =new TaskInfoBean();
allTaskList.add(taskInfo);
askInfo.packageName = appProcessInfo.processName;
// 输入多少个进程ID,返回多少个 内存信息
android.os.Debug.MemoryInfo[] processMemoryInfo = am.getProcessMemoryInfo(new int[]{appProcessInfo.pid});
// 获得内存信息
taskInfo.memSize = processMemoryInfo[0].getTotalPrivateDirty()*1024; // 返回的是kb 而我们要的是byte
try {
ApplicationInfo applicationInfo = pm.getApplicationInfo(taskInfo.packageName, 0);
// 获得图标
taskInfo.appIcon = applicationInfo.loadIcon(pm);
// 获得名称
taskInfo.appName = applicationInfo.loadLabel(pm).toString();
// 设置是否是系统应用
if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)!=0){ // 不等于0 说明批配成功
taskInfo.isSys = true;
}else{
taskInfo.isSys = false;
}
} catch (Exception e) {
e.printStackTrace();
// 如果抛了异常,说明是C代码
taskInfo.isSys = true;
// 设置图标
taskInfo.appIcon = ctx.getResources().getDrawable(R.drawable.ic_launcher);
// 设置名称
taskInfo.appName = appProcessInfo.processName;
}
}
return allTaskList;
};
}
获得联系人
public class ContactsUtils {
public static class Contact {
public String name;
public String phone;
public String address;
public String email;
@Override
public String toString() {
// TODO Auto-generated method stub
return name+","+phone+","+address+","+email;
}
}
public static ArrayList<Contact> getAllContacts(Context context) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Contact> contacts = null;
Contact contact = null;
// 是raw_contacts表
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
// data表的路径
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = context.getContentResolver().query(uri,new String[] { "contact_id" }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
contacts = new ArrayList<ContactsUtils.Contact>();
// 这个拿到的是有几个联系人,并且每个联系人的id拿到
while (cursor.moveToNext()) {
String id = cursor.getString(0);
//这做非空判断的目的,是因为删除联系人只是将raw_contact表中的一个id置为null,data表并没有做修改
if(id!=null){
//再去new对象,保证这个id没有被删除
contact = new Contact();
setValueToContact(context, contact, dataUri, id);
System.out.println("联系人的id" + id);
// 我们只关心数据类型,和数据实体,用刚才拿到的id作为筛选条件,先拿到一个人的全部数据
//赋值的操作,需要查询另一个表,为了让层次关系更清晰,这里单独拿一个方法出来
contacts.add(contact);
}
}
cursor.close();
}
return contacts;
}
/**
* 给每个Contact赋值
* @param context
* @param contact
* @param dataUri
* @param id
*/
private static void setValueToContact(Context context, Contact contact,Uri dataUri, String id) {
// 我们只关心数据类型,和数据实体,用刚才拿到的id作为筛选条件,先拿到一个人的全部数据
//通过查询所有列名,发现没有mimetype_id这一列,只有mimetype
Cursor dataCursor = context.getContentResolver().query(dataUri,new String[] { "mimetype", "data1" },"raw_contact_id = ?", new String[] { id }, null);
if (dataCursor != null && dataCursor.getCount() > 0) {
while (dataCursor.moveToNext()) {
//数据类型
String mimetype = dataCursor.getString(0);
//数据实体
String data = dataCursor.getString(1);
System.out.println("数据类型:" + mimetype + ",数据实体:" + data);
if (mimetype.equals("vnd.android.cursor.item/phone_v2")) {
// 代表是一个电话类型的数据
contact.phone = data;
} else if (mimetype.equals("vnd.android.cursor.item/email_v2")) {
// 代表是一个邮箱类型的数据
contact.email = data;
} else if (mimetype.equals("vnd.android.cursor.item/postal-address_v2")) {
// 代表是一个地址类型的数据
contact.address = data;
} else if (mimetype.equals("vnd.android.cursor.item/name")) {
// 代表是姓名类型的数据
contact.name = data;
}
}
dataCursor.close();
}
}
}
监听系统音量改变改变进度条
AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE) ;
sound = (SeekBar) findViewById(R.id.sb_sound);
/**
* 注册当音量发生变化时接收的广播
*/
private void myRegisterReceiver(){
mVolumeReceiver = new MyVolumeReceiver() ;
IntentFilter filter = new IntentFilter() ;
filter.addAction("android.media.VOLUME_CHANGED_ACTION") ;
registerReceiver(mVolumeReceiver, filter) ;
}
/**
* 处理音量变化时的界面显示
* @author long
*/
private class MyVolumeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//如果音量发生变化则更改seekbar的位置
if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
int currVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;// 当前的媒体音量
sound.setProgress(currVolume) ;
}
}
}