【问题标题】:Why Toast.maketoast is not working in the BroadcastReceiver class为什么 Toast.maketoast 在 BroadcastReceiver 类中不起作用
【发布时间】:2016-12-12 15:50:00
【问题描述】:

我在尝试调用 BroadcastReceiver 类型类的 onReceive 函数中的 Toast.makeText 函数时收到错误消息。 这不是 another Question 的重复,因为我正在调用 show() 方法,这是编译时问题 错误是:无法解析方法 makeText。

如果我在任何其他活动类型类中调用它,相同的函数工作正常。

这是我正在尝试运行的代码。

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class CallStateReceiver  extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
    }
}

【问题讨论】:

标签: android android-studio android-broadcastreceiver android-toast


【解决方案1】:

我猜context 有问题。将其更改为:

Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();

【讨论】:

    【解决方案2】:

    Context 从 BroadcastReceiver 类传递给 Toast。如下所示更改您的 toast onReceive 方法

    @Override
     public void onReceive(Context context, Intent intent) {
    
      Toast.makeText(context,"test", Toast.LENGTH_SHORT).show();
     }
    

    【讨论】:

      【解决方案3】:

      改变这个

      Toast.makeText(this,"test", Toast.LENGTH_SHORT).show();
      

      到这里

      Toast.makeText(context,"test", Toast.LENGTH_SHORT).show();
      

      试试

      【讨论】:

        猜你喜欢
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        相关资源
        最近更新 更多