【发布时间】:2011-04-26 16:56:39
【问题描述】:
我正在尝试让我的 IntentService 显示 Toast 消息, 但是当从 onHandleIntent 消息发送它时,吐司显示但卡住了,屏幕永远不会离开。 我猜是因为 onHandleIntent 方法不会发生在主服务线程上,但是我该如何移动它呢?
有人遇到过这个问题并解决了吗?
【问题讨论】:
标签: android multithreading intentservice android-toast
我正在尝试让我的 IntentService 显示 Toast 消息, 但是当从 onHandleIntent 消息发送它时,吐司显示但卡住了,屏幕永远不会离开。 我猜是因为 onHandleIntent 方法不会发生在主服务线程上,但是我该如何移动它呢?
有人遇到过这个问题并解决了吗?
【问题讨论】:
标签: android multithreading intentservice android-toast
这里是完整的 IntentService 类代码,展示了对我有帮助的 Toast:
package mypackage;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
public class MyService extends IntentService {
public MyService() { super("MyService"); }
public void showToast(String message) {
final String msg = message;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
@Override
protected void onHandleIntent(Intent intent) {
showToast("MyService is handling intent.");
}
}
【讨论】:
使用 Handle 发布一个 Runnable,其中包含您的操作
protected void onHandleIntent(Intent intent){
Handler handler=new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
public void run(){
//your operation...
Toast.makeText(getApplicationContext(), "hello world", Toast.LENGTH_SHORT).show();
}
});
【讨论】:
在onCreate() 中初始化一个Handler,然后从您的线程中发布到它。
private class DisplayToast implements Runnable{
String mText;
public DisplayToast(String text){
mText = text;
}
public void run(){
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
protected void onHandleIntent(Intent intent){
...
mHandler.post(new DisplayToast("did something"));
}
【讨论】:
cancel方法
mHandler = new Handler(Looper.getMainLooper());