Big Bug Ban

兴趣 践行 创新

Android开发日志 线程安全 小总结

 

本文已经参加   “首届 Google 暑期大学生博客分享大赛——2010 Android 篇”

为princehaku原创   如果您忘了我的地址  请使用google搜索  “Android开发日志”

今天弄了一天的这个软件…

最大的感受就是..

线程安全..既可靠又可恨,,

可恨的是每次都得重新写了Handler..不然不能调用..

比如alert

如果我在线程中直接调用了个alert..将会报错..

下面这个类是一个alert框体.

/**
 * Copyright (c) 2010 princehaku
 * All right reserved.
 * Author princehaku
 * Site http://haku.hk
 * Created on : 2010-8-8, 10:12:28
 */
package org.me.androidkvb;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**消息提示类
 *
 * @author princehaku
 */
public class Alert {

    /**资源
     *
     */
    private static Context res;

    Dialog alert;

    /**从上级资源中构建
     * res一般是当前活动的Activity
     * @param res
     */
    Alert(Context res) {
        this.res = res;
    }
    /**显示对话框
     *
     * @param title
     * @param message
     */
    public void show(String title,String message) {
        Message msg = new Message();
        Bundle ble = new Bundle();
        ble.putString("title", title);
        ble.putString("msg", message);
        msg.setData(ble);
        this.alertHandler.sendMessage(msg);
    }

    /**隐藏对话框
     *
     */
    public void destory() {
        if(alert!=null){
            alert.dismiss();
        }
    }
    /**隐含的方法
     * 显示对话框
     * @param info
     */
    private void alert(String title,String info) {
        if (alert != null) {
            alert.dismiss();
        }
        alert = new AlertDialog.Builder(res).setIcon(android.R.drawable.ic_dialog_alert).setTitle(title).setMessage(info).show();
    }
    /**Hander
     * 保证线程安全
     */
    public Handler alertHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            alert(msg.getData().getString("title"),msg.getData().getString("msg"));
            super.handleMessage(msg);
        }
    };
}

使用的时候如下

/**
 *
 * @author princehaku
 */
public class MainActivity extends Activity implements OnClickListener{
    Alert alert;
    public Alert getAlert(){
        if(alert==null)alert=new Alert(this);
        return alert;
    }
 public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
       Thread t=new Thread(){
        @Override
        public void run() {
                    getAlert().show("Please Wait","开始联网获取课表信息");
               }
        };
    t.start();
}

不仅仅是这个…只要非安全线程调用都得用Handler去处理

=================================================

哎…看来还得写很多…因为多线程的用户体验比单线程好..

如果超过5秒就会提示退出了..

so…coding…

另外…进度展示

已经可以解释出序列化的课表了..

也可以显示出来…还有具体解析时的进度  自己弄了个假的条形的进度条…

Written by princehaku

8 8 月, 2010 at 3:32 下午

Posted in Android

Tagged with ,

with 2 comments

2 Responses to 'Android开发日志 线程安全 小总结'

Subscribe to comments with RSS or TrackBack to 'Android开发日志 线程安全 小总结'.

  1. haku,好可恨啊,以来就又搜到你的网站!

    momo

    4 11 月 11 at 5:31 下午

  2. 额…这个.

    princehaku

    4 11 月 11 at 9:08 下午

Leave a Reply