【问题标题】:How to create toast from IntentService? It gets stuck on the screen如何从 IntentService 创建吐司?它卡在屏幕上
【发布时间】:2011-04-26 16:56:39
【问题描述】:

我正在尝试让我的 IntentService 显示 Toast 消息, 但是当从 onHandleIntent 消息发送它时,吐司显示但卡住了,屏幕永远不会离开。 我猜是因为 onHandleIntent 方法不会发生在主服务线程上,但是我该如何移动它呢?

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

【问题讨论】:

标签: android multithreading intentservice android-toast


【解决方案1】:

这里是完整的 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.");
    }
}

【讨论】:

  • 不可能使用 Application-Context 创建 Toast ...您需要一个 Activity 来执行此类操作 ...
  • @VallaDanger 我提供了一个真实的工作代码 sn-p。
【解决方案2】:

使用 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();
    }  
}); 

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 你的 mContext 初始化成什么?
    • 是对服务的引用。
    • 这样烤出来的吐司不会消失。除了上面的代码还有什么我应该添加的吗?
    • @Yulong 这是一个有趣的bug,你可以随时保留toast的引用并调用它的cancel方法
    • @AvinashR 来解决这个问题,只需使用带有 Looper 的 Handler 构造函数。 mHandler = new Handler(Looper.getMainLooper());
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    相关资源
    最近更新 更多