我试图让我的 IntentService 显示一条 Toast 消息,但是当从 onHandleIntent 消息发送它时,toast 显示但卡住了,屏幕也没有离开。我猜是因为 onHandleIntent 方法不会发生在主服务线程上,但是我该如何移动它呢?
有没有人遇到这个问题并解决了?
我试图让我的 IntentService 显示一条 Toast 消息,但是当从 onHandleIntent 消息发送它时,toast 显示但卡住了,屏幕也没有离开。我猜是因为 onHandleIntent 方法不会发生在主服务线程上,但是我该如何移动它呢?
有没有人遇到这个问题并解决了?
在onCreate()初始化 aHandler然后从您的线程发布到它。
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"));
}
这是完整的 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();
}
});