IntentService(或非UI线程)中使用Toast

来源:互联网 发布:sd格式化数据恢复 编辑:程序博客网 时间:2024/05/23 20:54

借鉴:

http://blog.csdn.net/xiaanming/article/details/8904645



1.说明

Toast要求必须再UI线程中才能显示,Service默认是再主UI线程上,而IntentService默认是在非ui线程上,所以在IntentServie中使用Toast实际上就是在非UI线程下使用Toast.




2.使用

方法一(推荐):
    private void showToastByRunnable(final IntentService context, final CharSequence text, final int duration)     {        Handler handler = new Handler(Looper.getMainLooper());        handler.post(new Runnable() {            @Override            public void run() {                Toast.makeText(context, text, duration).show();            }        });    }


方法二:

重写Toast的show方法

Toast里面的show()      public void show() {        ...          service.enqueueToast(pkg, tn, mDuration);   //把这个toast插入到一个队列里面          ...      }  


0 0
原创粉丝点击