标签:
新建一个类MyApplication,继承自Application。代码如下:
MyApplication.java:
1 package com.smyhvae.homepicdemo; 2 3 import android.app.Application; 4 import android.os.Handler; 5 import android.os.Looper; 6 7 /** 8 * Created by smyhvae on 2015/5/13. 9 */ 10 public class MyApplication extends Application { 11 //获取到主线程的上下文 12 private static MyApplication mContext = null; 13 //获取到主线程的handler 14 private static Handler mMainThreadHandler = null; 15 //获取到主线程的looper 16 private static Looper mMainThreadLooper = null; 17 //获取到主线程 18 private static Thread mMainThead = null; 19 //获取到主线程的id 20 private static int mMainTheadId; 21 22 @Override 23 public void onCreate() { 24 // TODO Auto-generated method stub 25 super.onCreate(); 26 this.mContext = this; 27 this.mMainThreadHandler = new Handler(); 28 this.mMainThreadLooper = getMainLooper(); 29 this.mMainThead = Thread.currentThread(); 30 //android.os.Process.myUid() 获取到用户id 31 //android.os.Process.myPid()获取到进程id 32 //android.os.Process.myTid()获取到调用线程的id 33 this.mMainTheadId = android.os.Process.myTid(); 34 } 35 36 public static MyApplication getApplication() { 37 return mContext; 38 } 39 40 public static Handler getMainThreadHandler() { 41 return mMainThreadHandler; 42 } 43 44 public static Looper getMainThreadLooper() { 45 return mMainThreadLooper; 46 } 47 48 public static Thread getMainThread() { 49 return mMainThead; 50 } 51 52 public static int getMainThreadId() { 53 return mMainTheadId; 54 } 55 56 }
然后记得在清单文件中进行声明:
1 <application 2 android:allowBackup="true" 3 android:icon="@mipmap/ic_launcher" 4 android:label="@string/app_name" 5 android:theme="@style/AppTheme" 6 android:name=".MyApplication">
需要声明的是上方代码的第6行android:name的属性。
Android代码优化----Application节点的模板写法
标签:
原文地址:http://www.cnblogs.com/smyhvae/p/4500858.html