天天看点

【移动开发】Android应用程序中实用的代码框架(二)

【移动开发】Android应用程序中实用的代码框架(二)

细心地大家可能会发现要是任务在10个以下,框架还可以承担,要是任务过多时(主要是并发执行时),

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<code>/**</code>

<code>     </code><code>* 线程不断检测tasks中的任务</code>

<code>     </code><code>*/</code>

<code>    </code><code>@Override</code>

<code>    </code><code>public</code> <code>void</code> <code>run() {</code>

<code>        </code><code>while</code><code>(isRun) {</code>

<code>            </code><code>Task task = </code><code>null</code><code>;</code>

<code>            </code><code>if</code><code>(!tasks.isEmpty()) {</code>

<code>                </code><code>task = tasks.poll();</code>

<code>                </code><code>if</code><code>(</code><code>null</code> <code>!= task) {</code>

<code>                    </code><code>doTask(task); </code><code>//处理任务</code>

<code>                </code><code>}</code>

<code>            </code><code>}</code>

<code>            </code><code>try</code> <code>{</code>

<code>                </code><code>Thread.sleep(</code><code>1000</code><code>);</code>

<code>            </code><code>} </code><code>catch</code> <code>(InterruptedException e) {</code>

<code>                </code><code>e.printStackTrace();</code>

<code>        </code><code>}</code>

<code>    </code><code>}</code>

鉴于实际开发中并发执行任务的情况较多!我整理了又一款非常实用的代码框架,也可以说是上次代码框架的加强版!

这次我采用了线程池的方式处理多任务,提高程序的运行效率。

<a href="http://blog.51cto.com/attachment/201311/111541752.jpg" target="_blank"></a>

首先是简单的一些类

IActivity类

<code>package</code> <code>com.zhf.android_frameworkdemo03.threadpool;</code>

<code>public</code> <code>interface</code> <code>IActivity {</code>

<code>    </code><code>/**</code>

<code>     </code><code>* 初始化操作</code>

<code>    </code><code>public</code> <code>abstract </code><code>void</code> <code>init();</code>

<code>     </code><code>* 刷新操作</code>

<code>     </code><code>* @param params 可变参数</code>

<code>    </code><code>public</code> <code>abstract </code><code>void</code> <code>refresh(</code><code>Object</code><code>... params);</code>

<code>}</code>

TaskID类:

<code>package</code> <code>com.zhf.android_frameworkdemo03.model;</code>

<code>public</code> <code>class</code> <code>TaskID {</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   </code> 

<code>    </code><code>public</code> <code>static</code> <code>final</code> <code>int</code> <code>MANAGER_LOGIN = </code><code>0</code><code>;</code><code>// 管理员登录</code>

<code>    </code><code>//以此类推,根据自己项目的需求添加任务ID</code>

TaskOperate类:

<code> </code><code>* 任务操作接口</code>

<code> </code><code>* @author ZHF</code>

<code> </code><code>*</code>

<code> </code><code>*/</code>

<code>public</code> <code>interface</code> <code>TaskOperate {</code>

<code>     </code><code>* 操作Task</code>

<code>     </code><code>* @param Task Task实体</code>

<code>    </code><code>public</code> <code>abstract </code><code>void</code> <code>operate(Task Task);</code>

接下来是重要的类

ThreadPoolManager类:

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

<code>import</code> <code>java.util.Collections;</code>

<code>import</code> <code>java.util.LinkedList;</code>

<code>import</code> <code>java.util.List;</code>

<code>import</code> <code>android.util.Log;</code>

<code> </code><code>* 线程池管理器</code>

<code>public</code> <code>class</code> <code>ThreadPoolManager {</code>

<code>    </code><code>public</code> <code>static</code> <code>String TAG = </code><code>"ThreadPoolManager"</code><code>;</code>

<code>    </code><code>public</code> <code>static</code> <code>ThreadPoolManager instance = </code><code>null</code><code>;</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       </code> 

<code>    </code><code>//Returns a wrapper on the specified List which synchronizes all access to the List.</code>

<code>    </code><code>public</code> <code>static</code> <code>List&lt;Task&gt; taskQueue = Collections.synchronizedList(</code><code>new</code> <code>LinkedList()); </code><code>//任务队列(LinkedList:便于插入和删除)</code>

<code>    </code><code>private</code> <code>WorkThread[] workQueue;  </code><code>//运行的线程数组</code>

<code>    </code><code>private</code> <code>static</code> <code>int</code> <code>threadNumber = </code><code>5</code><code>;  </code><code>//线程池数量5</code>

<code>    </code><code>/**构造方法(单例)**/</code>

<code>    </code><code>private</code> <code>ThreadPoolManager(TaskOperate taskOperate) {</code>

<code>        </code><code>this</code><code>(threadNumber, taskOperate);</code>

<code>    </code><code>/**构造方法(单例):实例化线程数组**/</code>

<code>    </code><code>private</code> <code>ThreadPoolManager(</code><code>int</code> <code>threadNumber, TaskOperate taskOperate) {</code>

<code>        </code><code>this</code><code>.threadNumber = threadNumber;</code>

<code>        </code><code>this</code><code>.workQueue = </code><code>new</code> <code>WorkThread[threadNumber];  </code><code>//装线程数组</code>

<code>        </code><code>for</code> <code>(</code><code>int</code> <code>i = </code><code>0</code><code>; i &lt; threadNumber; i++) {</code>

<code>            </code><code>this</code><code>.workQueue[i] = </code><code>new</code> <code>WorkThread(i, taskOperate); </code><code>//将线程对应装入数组</code>

<code>            </code><code>System.out.println(</code><code>"当前运行的是"</code><code>+ i +</code><code>"个线程"</code><code>);</code>

<code>    </code><code>/**获取该类的实例对象(懒汉式)**/</code>

<code>    </code><code>public</code> <code>static</code> <code>synchronized</code> <code>ThreadPoolManager getInstance(TaskOperate taskOperate) {</code>

<code>        </code><code>if</code><code>(instance == </code><code>null</code><code>) {</code>

<code>            </code><code>instance = </code><code>new</code> <code>ThreadPoolManager(taskOperate);</code>

<code>            </code><code>return</code> <code>instance; </code><code>//获取实例</code>

<code>        </code><code>return</code> <code>null</code><code>;</code>

<code>    </code><code>/**添加单个任务**/</code>

<code>    </code><code>public</code> <code>void</code> <code>addTask(Task task) {</code>

<code>        </code><code>synchronized</code><code>(taskQueue) { </code><code>//锁住线程队列对象</code>

<code>            </code><code>if</code><code>(task != </code><code>null</code><code>) {</code>

<code>                </code><code>taskQueue.add(task);</code>

<code>                </code><code>taskQueue.notifyAll();</code>

<code>                </code><code>System.out.println(</code><code>"任务: "</code> <code>+ task.getTaskInfo() + </code><code>"--添加成功--"</code><code>);</code>

<code>    </code><code>/**添加多个任务**/</code>

<code>    </code><code>public</code> <code>void</code> <code>addTasks(Task[] tasks) {</code>

<code>        </code><code>synchronized</code> <code>(taskQueue) { </code><code>//锁住线程队列对象</code>

<code>            </code><code>for</code> <code>(Task t : tasks) { </code><code>//遍历</code>

<code>                </code><code>if</code><code>(tasks != </code><code>null</code><code>) {</code>

<code>                    </code><code>taskQueue.add(t);</code>

<code>                    </code><code>taskQueue.notifyAll();</code>

<code>                    </code><code>System.out.println(</code><code>"任务: "</code> <code>+ t.getTaskInfo() + </code><code>"--添加成功--"</code><code>);</code>

<code>    </code><code>/**销毁线程**/</code>

<code>    </code><code>public</code> <code>void</code> <code>destroy() {</code>

<code>        </code><code>Log.i(TAG, </code><code>"线程池管理器destroy方法开始。。。"</code><code>);</code>

<code>            </code><code>this</code><code>.workQueue[i].stopThread(); </code><code>//停止线程</code>

<code>            </code><code>this</code><code>.workQueue[i] = </code><code>null</code><code>;  </code><code>//GC回收</code>

<code>            </code><code>//清空队列集合</code>

<code>            </code><code>taskQueue.clear();</code>

<code>        </code><code>Log.i(TAG, </code><code>"线程池管理器destroy方法结束。。。"</code><code>);</code>

<code>        </code><code>System.gc(); </code><code>//内存回收</code>

说明:

1.这里我并没有使用ThreadPoolExecutor来真正的实现线程池操作,而是用数组装载线程的方式模拟线程池操作,在实例化该类的时候(程序启动时)我们开启了5个WorkThread在后台等待执行任务。

2.该类还有两个重要的方法:

addTask()----&gt;添加具体任务到任务队列

destroy() ----&gt;销毁线程

WorkThread类:

<code> </code><code>* 工作线程</code>

<code>public</code> <code>class</code> <code>WorkThread </code><code>extends</code> <code>Thread {</code>

<code>    </code><code>private</code> <code>int</code> <code>taskId;  </code><code>//任务Id</code>

<code>    </code><code>private</code> <code>boolean</code> <code>isRunning = </code><code>true</code><code>;  </code><code>//线程启动标记</code>

<code>    </code><code>private</code> <code>TaskOperate taskOperate;  </code><code>//任务操作接口</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        </code> 

<code>    </code><code>/**构造方法:启动线程**/</code>

<code>    </code><code>public</code> <code>WorkThread(</code><code>int</code> <code>taskId, TaskOperate taskOperate) {</code>

<code>        </code><code>this</code><code>.taskId = taskId;</code>

<code>        </code><code>this</code><code>.taskOperate = taskOperate;</code>

<code>        </code><code>//启动</code>

<code>        </code><code>this</code><code>.start();</code>

<code>        </code><code>while</code><code>(isRunning) {</code>

<code>            </code><code>synchronized</code> <code>(ThreadPoolManager.taskQueue) { </code><code>//线程队列</code>

<code>                </code><code>//线程虽然开启,但是没有任务队列中没有添加具体任务进来</code>

<code>                </code><code>while</code><code>(isRunning &amp;&amp; ThreadPoolManager.taskQueue.isEmpty()) {</code>

<code>                    </code><code>try</code> <code>{</code>

<code>                        </code><code>ThreadPoolManager.taskQueue.wait(20L);</code>

<code>                    </code><code>} </code><code>catch</code> <code>(InterruptedException e) {</code>

<code>                        </code><code>System.out.println(</code><code>"线程"</code> <code>+ </code><code>this</code><code>.taskId + </code><code>"在运行时,报InterruptedException"</code><code>);</code>

<code>                        </code><code>Log.e(ThreadPoolManager.TAG, </code><code>"线程"</code> <code>+ </code><code>this</code><code>.taskId + </code><code>"在运行时,报InterruptedException"</code><code>);</code>

<code>                        </code><code>e.printStackTrace();</code>

<code>                    </code><code>}</code>

<code>                </code><code>if</code><code>(</code><code>this</code><code>.isRunning) {</code>

<code>                    </code><code>//移除任务</code>

<code>                    </code><code>task = ThreadPoolManager.taskQueue.remove(</code><code>0</code><code>);</code>

<code>            </code><code>//有任务进来</code>

<code>                </code><code>System.out.println(task.getTaskInfo() + </code><code>"任务在线程"</code><code>+ </code><code>this</code><code>.taskId + </code><code>"中开始。。。"</code><code>);</code>

<code>                 </code><code>//处理任务(调用接口中方法处理,具体实现在子类当中。多态)</code>

<code>                </code><code>this</code><code>.taskOperate.operate(task);</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    </code> 

<code>                </code><code>System.out.println(task.getTaskInfo() + </code><code>"任务在线程"</code> <code>+ </code><code>this</code><code>.taskId + </code><code>"结束中。。。"</code><code>);</code>

<code>    </code><code>/**停止线程**/</code>

<code>    </code><code>public</code> <code>void</code> <code>stopThread() {</code>

<code>        </code><code>this</code><code>.isRunning = </code><code>false</code><code>;</code>

该类是一个线程类,主要用于处理任务队列中任务事件,5个线程共同处理任务集合中的task,避免了先前一个线程处理task时,后一个task等待的情况,提高了系统的执行效率!

ClientTask类:

<code>package</code> <code>com.zhf.android_frameworkdemo03.services;</code>

<code>import</code> <code>android.os.Handler;</code>

<code>import</code> <code>android.os.Message;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.MyApplication;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.handle.LoginHandler;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.model.TaskID;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.threadpool.IActivity;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.threadpool.Task;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.threadpool.TaskOperate;</code>

<code> </code><code>* 统一处理任务类</code>

<code>public</code> <code>class</code> <code>ClientTask </code><code>implements</code> <code>TaskOperate{</code>

<code>    </code><code>/**统一任务处理**/</code>

<code>    </code><code>public</code> <code>void</code> <code>operate(Task task) {</code>

<code>        </code><code>Message message = mHandler.obtainMessage();</code>

<code>        </code><code>message.what = task.getId();</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                         </code> 

<code>        </code><code>//1.根据TaskID来判断,调用对应的XXhandler来处理任务</code>

<code>        </code><code>//2.处理完成得到返回的message.obj数据,将其统一sendMessage(message)出去</code>

<code>        </code><code>//3.在消息处理机制mHandler中对应接收数据,刷新对应的UI界面</code>

<code>        </code><code>switch</code> <code>(task.getId()) {</code>

<code>        </code><code>case</code> <code>TaskID.MANAGER_LOGIN: </code><code>//管理员登陆</code>

<code>            </code><code>//处理登录事件,获取message.obj数据</code>

<code>            </code><code>LoginHandler.getLogin(task, message);</code>

<code>            </code><code>break</code><code>;</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                             </code> 

<code>            </code><code>//此处添加后续任务</code>

<code>        </code><code>mHandler.sendMessage(message);</code><code>//发送消息</code>

<code>    </code><code>/**消息处理**/</code>

<code>    </code><code>public</code> <code>Handler mHandler = </code><code>new</code> <code>Handler() {</code>

<code>        </code><code>@Override</code>

<code>        </code><code>public</code> <code>void</code> <code>handleMessage(Message msg) {</code>

<code>            </code><code>super</code><code>.handleMessage(msg);</code>

<code>            </code><code>IActivity ia = </code><code>null</code><code>;</code>

<code>            </code><code>//根据传来的任务消息ID,来对应的传递参数刷新界面</code>

<code>            </code><code>switch</code> <code>(msg.what) {</code>

<code>            </code><code>case</code> <code>TaskID.MANAGER_LOGIN:  </code><code>//管理员登陆</code>

<code>                </code><code>ia = MyApplication.getActivityByName(</code><code>"MainActivity"</code><code>);</code>

<code>                </code><code>ia.refresh(msg.obj);</code>

<code>                </code><code>break</code><code>;</code>

<code>                                                                                                                                                                                                                                                                                                                                                                                                                 </code> 

<code>    </code><code>};</code>

1.该类实现了先前定义的TaskOperate接口,重写了operate()处理任务,对应TaskID我们新建了一个类LoginHandler来处理,最后接收处理结果message.obj,并统一发送到mHandler接收,刷新对应的UI界面。

2.注意:该类我们实现的是客户端的一系列请求任务,当然我们还可以再定义一个类,实现TaskOperate接口,用于统一操作服务器端Task,也是可以的,扩展么!)

LoginHandler类:

<code>package</code> <code>com.zhf.android_frameworkdemo03.handle;</code>

<code> </code><code>* 登录事件处理</code>

<code>public</code> <code>class</code> <code>LoginHandler {</code>

<code>                                                                                                                                                                                                    </code> 

<code>    </code><code>/**处理登录事物,将结果用消息发送出去**/</code>

<code>    </code><code>public</code> <code>static</code> <code>void</code> <code>getLogin(Task task, Message message) {</code>

<code>        </code><code>//处理完成。。。。</code>

<code>        </code><code>message.obj = </code><code>"登陆成功!"</code><code>;</code>

程序入口

MainActivity类:

<code>package</code> <code>com.zhf.android_frameworkdemo03;</code>

<code>import</code> <code>android.os.Bundle;</code>

<code>import</code> <code>android.view.View;</code>

<code>import</code> <code>android.view.View.OnClickListener;</code>

<code>import</code> <code>android.widget.Button;</code>

<code>import</code> <code>android.widget.TextView;</code>

<code>import</code> <code>android.app.Activity;</code>

<code>public</code> <code>class</code> <code>MainActivity </code><code>extends</code> <code>Activity </code><code>implements</code> <code>IActivity{</code>

<code>                                                                                                                                                             </code> 

<code>    </code><code>public</code> <code>Button mBtnLogin; </code><code>//登陆按钮:测试代码框架是否运行正常</code>

<code>    </code><code>public</code> <code>TextView mTvLogin;</code>

<code>    </code><code>protected</code> <code>void</code> <code>onCreate(Bundle savedInstanceState) {</code>

<code>        </code><code>super</code><code>.onCreate(savedInstanceState);</code>

<code>        </code><code>setContentView(R.layout.activity_main);</code>

<code>                                                                                                                                                                 </code> 

<code>        </code><code>//1.将要执行任务的Activity,加入到集合中</code>

<code>        </code><code>MyApplication.allActivity.add(</code><code>this</code><code>);</code>

<code>        </code><code>this</code><code>.mBtnLogin = (Button) findViewById(R.id.button1);</code>

<code>        </code><code>this</code><code>.mTvLogin = (TextView) findViewById(R.id.textView1);</code>

<code>        </code><code>mBtnLogin.setOnClickListener(</code><code>new</code> <code>OnClickListener() {</code>

<code>            </code><code>@Override</code>

<code>            </code><code>public</code> <code>void</code> <code>onClick(View v) {</code>

<code>                </code><code>//2.产生任务:对应填入参数</code>

<code>                </code><code>Task task = </code><code>new</code> <code>Task(TaskID.MANAGER_LOGIN, </code><code>"框架测试成功!!"</code><code>, </code><code>"---登陆任务----"</code><code>);</code>

<code>                </code><code>//3.将当前任务加入到写好的线程池中()</code>

<code>                </code><code>MyApplication.poolManager.addTask(task);</code>

<code>        </code><code>});</code>

<code>    </code><code>public</code> <code>void</code> <code>init() {</code>

<code>        </code><code>// TODO Auto-generated method stub</code>

<code>    </code><code>public</code> <code>void</code> <code>refresh(Object... params) {</code>

<code>        </code><code>//接收线程处理过后返回的数据</code>

<code>        </code><code>mTvLogin.setText(params[</code><code>0</code><code>].toString());</code>

MyApplication类:

<code>import</code> <code>java.util.ArrayList;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.services.ClientTask;</code>

<code>import</code> <code>com.zhf.android_frameworkdemo03.threadpool.ThreadPoolManager;</code>

<code>import</code> <code>android.app.Application;</code>

<code> </code><code>*加载配置文件,监测网络情况,初始化任务线程池</code>

<code>public</code> <code>class</code> <code>MyApplication </code><code>extends</code> <code>Application{</code>

<code>                                                                                                                                                                       </code> 

<code>    </code><code>// 所有实现接口IActivity的Activity,即放置所有要执行任务的Activity</code>

<code>    </code><code>public</code> <code>static</code> <code>ArrayList&lt;IActivity&gt; allActivity = </code><code>new</code> <code>ArrayList&lt;IActivity&gt;();</code>

<code>    </code><code>public</code> <code>static</code> <code>ThreadPoolManager poolManager;</code>

<code>    </code><code>/**程序启动**/</code>

<code>    </code><code>public</code> <code>void</code> <code>onCreate() {</code>

<code>        </code><code>super</code><code>.onCreate();</code>

<code>        </code><code>//程序启动时,开启线程池(5个线程,等待task)</code>

<code>        </code><code>poolManager = ThreadPoolManager.getInstance(</code><code>new</code> <code>ClientTask());</code>

<code>                                                                                                                                                                           </code> 

<code>    </code><code>/**根据名字获取Activity**/</code>

<code>    </code><code>public</code> <code>static</code> <code>IActivity getActivityByName(</code><code>String</code> <code>name) {</code>

<code>        </code><code>IActivity ia = </code><code>null</code><code>;</code>

<code>        </code><code>for</code> <code>(IActivity ac : allActivity) {</code>

<code>            </code><code>if</code> <code>(ac.getClass().getName().endsWith(name)) {</code>

<code>                </code><code>ia = ac;</code>

<code>        </code><code>return</code> <code>ia;</code>

到此,强大的代码框架已搭建起来,我们点击一下按钮,测试一下代码吧!

为了让大家看的更清楚,我打印出了后台数据!

<a href="http://blog.51cto.com/attachment/201311/152200402.jpg" target="_blank"></a>

为了显示出框架的威力!我们可以试试狂点按钮,通过后台数据,我们知道了每次处理该任务是不同的线程!

<a href="http://blog.51cto.com/attachment/201311/152339329.jpg" target="_blank"></a>

     本文转自zhf651555765 51CTO博客,原文链接:http://blog.51cto.com/smallwoniu/1324842,如需转载请自行联系原作者