我试图让我的意见力显示吐司消息,但是当从on handheNdleIntent消息发送时,吐司显示但被卡住了,屏幕却从未陷入困境。我猜它是因为主服务线程上没有发生术语方法,但是我该如何移动呢?

有人有这个问题并解决了吗?

有帮助吗?

解决方案

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")); 
}

其他提示

这是完整的意识服务类代码,展示了对我有帮助的吐司:

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.");
    }
}

使用手柄发布可运行的可满足您操作的可运行

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();
    }  
}); 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top