標籤:
建立一個類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 //擷取到主線程的handler14 private static Handler mMainThreadHandler = null;15 //擷取到主線程的looper16 private static Looper mMainThreadLooper = null;17 //擷取到主線程18 private static Thread mMainThead = null;19 //擷取到主線程的id20 private static int mMainTheadId;21 22 @Override23 public void onCreate() {24 // TODO Auto-generated method stub25 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() 擷取到使用者id31 //android.os.Process.myPid()擷取到進程id32 //android.os.Process.myTid()擷取到調用線程的id33 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 <application2 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節點的模板寫法