在IntentService中使用Toast与在Service中使用Toast的异同
1. 表象
Service中能够正常显示Toast,IntentService中不能正常显示Toast。在2.3系统上,不显示toast,在4.3系统上,toast显示。可是不会消失。
2. 问题分析
查阅Android官方文档能够发现:
Public Constructors
public Toast (Context context)
Construct an empty Toast object. You must call setView(View) before
 you can call show().
Parameters
| context | The context to use. Usually your Application or Activity object. | 
|---|
从上面能够看出:
Toast要求执行在UI主线程中。所以要想Toast可以正常工作那个必须把它发到UI线程中。
Service执行在主线程中。因此Toast是正常的。
IntentService执行在独立的线程中。因此Toast不正常。
3. 在IntentService中显示Toast
利用Handler,将显示Toast的工作,放在主线程中来做。
详细有两个实现方式。
方法一:Handler的post方式实现,这个方式比較简单。
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();
        }
    });
}
方法二:Handler的msg方式实现,这个方式比較复杂。
Handler msgHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(ToastIntentService.this,msg.getData().getString("Text"), Toast.LENGTH_SHORT).show();
        super.handleMessage(msg);
    }
};
private void showToastByMsg(final IntentService context, final CharSequence text, final int duration) {
    Bundle data = new Bundle();
    data.putString("Text", text.toString());
    Message msg = new Message();
    msg.setData(data);
    msgHandler.sendMessage(msg);
}
4. 关于耗时操作
Service中假设有耗时的操作,要开启一个Thread来做。
IntentService是在独立的线程中,所以能够进行一些耗时操作。
5. 考虑AsyncTask与Service的使用差别
假设是全后台的工作。使用Service。结果的提示能够使用Notification。
假设是异步工作,工作结束后须要更新UI,那么最好使用Thread或者AsyncTask。
6. 应用实例
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
sendList=intent.getStringArrayListExtra("sendList");
String content=intent.getStringExtra("content");
for (String number : sendList)
{
// 创建一个PendingIntent对象
PendingIntent pi = PendingIntent.getActivity(
SendService.this, 0, new Intent(), 0);
SmsManager sManager=SmsManager.getDefault();
// 发送短信
sManager.sendTextMessage(number, null,content, pi, null);
count++;
showMsg("发送给:"+number+"的短信已完毕");
}
// 提示短信群发完毕
showMsg("短信群发完毕");
}
//利用Handler,将显示Toast的工作,放在主(UI)线程中来做
public void showMsg(final String msg) {
// TODO Auto-generated method stub
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(SendService.this,msg,Toast.LENGTH_SHORT).show();
}
});
}
在IntentService中使用Toast与在Service中使用Toast的异同的更多相关文章
- Handler: Service中使用Toast
		
Handler 的使用在 android App 开发中用的颇多,它的作用也很大,使用 Handler 一般也会使用到多线程,相信大家对 Handler 不会陌生,在这里,重点说一下 android ...
 - (原创)在service中定时执行网络操作的几点说明
		
执行网络操作是耗时操作,即便是在service中也要放到子线程中执行 这里我用到了async-http-client框架来执行异步请求操作 计时用的java原生Timer和TimerTask类 本来这 ...
 - Android悬浮框,在Service中打开悬浮窗;在Service中打开Dialog;
		
文章介绍了如何在Service中显示悬浮框,在Service中弹出Dialog,在Service中做耗时的轮询操作: 背景需求: 公司的项目现在的逻辑是这样的:发送一个指令,然后3秒一次轮询去查询这个 ...
 - 使用Angular CDK实现一个Service弹出Toast组件
		
在Angular中,官方团队在开发Material组件库的同时,顺手做了一套Component dev kit,也就是在Angular世界中大名鼎鼎的CDK,这套工具包提供了非常多的前端开发的通用功能 ...
 - 如何托管ASP.NET Core应用到Windows Service中
		
(此文章同时发表在本人微信公众号"dotNET开发经验谈",欢迎右边二维码来关注.) 题记:正在构思一个中间件的设计,考虑是否既可以使用最新的技术,也可以兼顾传统的部署模式.所以有 ...
 - angularjs中provider,factory,service的区别和用法
		
angularjs中provider,factory,service的区别和用法 都能提供service,但是又有差别 service 第一次被注入时实例化,只实例化一次,整个应用的生命周期中是个单例 ...
 - Web Service 中返回DataSet结果大小改进
		
http://www.cnblogs.com/scottckt/archive/2012/11/10/2764496.html Web Service 中返回DataSet结果方法: 1)直接返回Da ...
 - 跟我学Windows Azure 四 Cloud Service中的WebRole与WorkRole,及他们之间的通信
		
Cloud Service 中WebRole就相当与我们的WebSite,而WorkRole相当与我们在服务器上写了个Windows Service,站在高可用的角度上来讲,Cloud Service ...
 - JAVA CDI 学习(5) - 如何向RESTFul Service中注入EJB实例
		
RESTFul Service中如果要注入EJB实例,常规的@Inject将不起作用,在Jboss中,应用甚至都启动不起来(因为@Inject注入失败),解决方法很简单:将@Inject换成@EJB ...
 
随机推荐
- android 时间与String的相互转化
			
:大体思路 [html] view plaincopy 这种转换要用到java.text.SimpleDateFormat类 字符串转换成日期类型: 方法1: 也是最简单的方法 Date date=n ...
 - 浅析MySQL各种索引
			
MySQL各种索引(由于是浅析大多都不刻意区分搜索引擎) INDEX(普通索引):最主要的索引.没有不论什么限制 ALTER TABLE `table_name` ADD INDEX index_na ...
 - 〖Linux〗VIM youcompleteme 自动补全 #include 文件名称
			
1. 拷贝配置文件 cp ~/.vim/bundle/YouCompleteMe/cpp/ycm/.ycm_extra_conf.py ~/.vim/.ycm_extra_conf.py 2. 修改配 ...
 - eval、exec、execfile
			
# -*- coding: utf-8 -*- #python 27 #xiaodeng #http://blog.csdn.net/azhao_dn/article/details/6921654 ...
 - c语言入门经典(第5版)
			
文章转载:http://mrcaoyc.blog.163.com/blog/static/23939201520159135915734 文件大小:126MB 文件格式:PDF [点击下载] C ...
 - 在shell中使用sed命令替换/为\/
			
sed命令相关: https://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856901.html https://www.cnblogs.com/D ...
 - 优股社区logo
 - HighCharts终极版本
			
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
 - (39)JS运动之缓冲运动
			
基本思路:使用定时器让物体向右运动,在运动的过程中再不是匀速运动,而是先快后慢,即距离越大,速度越快,距离越小,速度越小,可是到达终点的时候,必须注意要使用向上取整函数Math.ceil()和向下取整 ...
 - java获取某个范围内的一个随机数
			
一.取模操作 public static void main(String[] args){ for (int i = 1; i <= 20; i++){ int j = i % 11; Sys ...