Omr*_*mri 25 multithreading android intentservice android-toast
我正在尝试让我的IntentService显示Toast消息,但是当从onHandleIntent消息发送它时,toast显示但是卡住了屏幕并且从不离开.我猜它是因为onHandleIntent方法不会发生在主服务线程上,但是我怎么能移动呢?
有人有这个问题并解决了吗?
Nat*_*ann 34
在onCreate()初始化a 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"));
}
Run Code Online (Sandbox Code Playgroud)
以下是完整的IntentService类代码,演示了帮助我的Toasts:
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.");
}
}
Run Code Online (Sandbox Code Playgroud)