1,创建MyApplication继承Application
package com.examplexiaomo.xiaomo;
import android.R.anim;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
public class MyApplication extends Application {
//
private static Context mMainContext;
private static Handler mMainHandler;
private static long mMainThread;
@Override
public void onCreate() {
mMainContext = getApplicationContext();// 上下文
mMainHandler = new Handler();//主线程的handler
mMainThread = android.os.Process.myTid();// 主线程的ID号
super.onCreate();
}
/**
* @return the mMainContext
*/
public static Context getMainContext() {
return mMainContext;
}
/**
* @param mMainContext the mMainContext to set
*/
public static void setMainContext(Context mMainContext) {
MyApplication.mMainContext = mMainContext;
}
/**
* @return the mMainHandler
*/
public static Handler getMainHandler() {
return mMainHandler;
}
/**
* @param mMainHandler the mMainHandler to set
*/
public static void setMainHandler(Handler mMainHandler) {
MyApplication.mMainHandler = mMainHandler;
}
/**
* @return the mMainThread
*/
public static long getMainThread() {
return mMainThread;
}
/**
* @param mMainThread the mMainThread to set
*/
public static void setMainThread(long mMainThread) {
MyApplication.mMainThread = mMainThread;
}
}
2,然后做好一个UIUtiles的工具类:
package com.examplexiaomo.xiaomo.utils;
import com.examplexiaomo.xiaomo.MyApplication;
import android.R.anim;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
public class UIUtils {
/**
* 获取上下文*/
public static Context getMainContext(){
return MyApplication.getMainContext();
}
/**
* 获取资源*/
public static Resources getResources(){
return getMainContext().getResources();
}
/**
* 获取*/
public static String getString(int resId){
return getResources().getString(resId);
}
public static String[] getStringArray(int resId){
return getResources().getStringArray(resId);
}
public static int getColor( int resId ){
return getResources().getColor(resId);
}
/**
* 获取主线程的Handler*/
public static Handler getMainHandler(){
return MyApplication.getMainHandler();
}
/**
* 获取主线程ID号*/
public static long getMainThread(){
return MyApplication.getMainThread();
}
/**
* 安全的刷新UI操作*/
public static void postTaskSaftly(Runnable task){
long currentThread= android.os.Process.myTid();//当前线程
long mainThread= getMainThread();//主线程
if (mainThread==currentThread) {
task.run();
}else {
getMainHandler().post(task);
}
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(float dpValue) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(float pxValue) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
}