标签:android 耗时任务 looper handler anr
public class HandlerThread extends Thread { private int mPriority; private int mTid =-1; private Looper mLooper; publicHandlerThread(String name) { super(name); mPriority =Process.THREAD_PRIORITY_DEFAULT; } publicHandlerThread(String name, int priority) { super(name); mPriority =priority; } protected void onLooperPrepared() { } public void run() { mTid =Process.myTid(); Looper.prepare(); synchronized(this) { mLooper =Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } public Looper getLooper() { if (!isAlive()) { return null; } // If the threadhas been started, wait until the looper has been created. synchronized(this) { while(isAlive() && mLooper == null) { try { wait(); } catch(InterruptedException e) { } } } return mLooper; } public boolean quit(){ Looper looper =getLooper(); if (looper !=null) { looper.quit(); return true; } return false; } public intgetThreadId() { return mTid; } }此类就是继承了Thread类,使用此类时一定要注意必须start(),否则run()方法没有调用,handler机制也就没有建立起来。
public class BackService extends Service { private ServiceHandler serviceHandler; @Override public IBinder onBind(Intent arg0) { return null; } private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); onHandleIntent((Intent) msg.obj); // 在其参数startId跟最后启动该service时生成的ID相等时才会执行停止服务。 stopSelf(msg.arg1); } } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread("BackService"); thread.start(); Looper serviceLooper = thread.getLooper(); serviceHandler = new ServiceHandler(serviceLooper); } @Override public void onStart(Intent intent, int startId) { Message msg = serviceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; serviceHandler.sendMessage(msg); } protected void onHandleIntent(Intent intent) { //做你的异步任务 } }
标签:android 耗时任务 looper handler anr
原文地址:http://blog.csdn.net/w2865673691/article/details/46048793