summaryrefslogtreecommitdiff
path: root/src/com/amlogic/pppoe/LooperThread.java (plain)
blob: af7fa3be4c123cc794f3c944f1fd536685201ce6
1package com.amlogic.pppoe;
2
3import android.util.Log;
4import android.os.Handler;
5import android.os.Looper;
6import android.os.Message;
7import android.os.MessageQueue;
8
9import java.util.LinkedList;
10
11public class LooperThread extends Thread {
12 private static final String TAG = "LooperThread";
13 private LinkedList<RunnableImpl> mQueue = new LinkedList();
14 private Impl mHandler = null;
15 private Looper mLooper = null;
16
17 public LooperThread() {
18 setName("PPPOE.LooperThread");
19 }
20
21 public void run() {
22 mLooper = Looper.myLooper();
23 Looper.prepare();
24 mHandler = new Impl();
25 Looper.loop();
26 }
27
28 public void post(RunnableImpl runnableimpl) {
29 if(runnableimpl == null) {
30 Log.w(TAG, "post runnableimpl is null!");
31 return;
32 }
33 synchronized (mQueue) {
34 mQueue.add(runnableimpl);
35 if (mQueue.size() == 1) {
36 scheduleNextLocked();
37 }
38 }
39 }
40
41 public RunnableImpl getLast() {
42 synchronized (mQueue) {
43 if (mQueue.size() > 0) {
44 return mQueue.getLast();
45 }
46 else {
47 return null;
48 }
49 }
50 }
51
52 public void cancelRunnable(RunnableImpl runnableimpl) {
53 synchronized (mQueue) {
54 while (mQueue.remove(runnableimpl)) { }
55 }
56 }
57
58 public void cancel() {
59 synchronized (mQueue) {
60 mQueue.clear();
61 }
62 }
63
64 private void scheduleNextLocked() {
65 if (mQueue.size() > 0) {
66 if(mHandler == null) {
67 Log.w(TAG, "scheduleNextLocked, mHandler is null!");
68 return;
69 }
70 mHandler.sendEmptyMessage(1);
71 }
72 }
73
74 public void stopThread(){
75 if (null != mLooper){
76 mLooper.quit();
77 }
78 }
79
80 private class Impl extends Handler {
81 public void handleMessage(Message msg) {
82 RunnableImpl r;
83 synchronized (mQueue) {
84 if (mQueue.size() == 0) {
85 Log.w(TAG, "mQueue is empty, don't do nothing!");
86 return;
87 }
88 r = mQueue.removeFirst();
89 }
90 if((r != null) && (r.mRunnable != null))
91 r.mRunnable.run();
92 synchronized (mQueue) {
93 scheduleNextLocked();
94 }
95 }
96 }
97}
98