【问题标题】:Toast on Broadcast receiver广播接收器上的吐司
【发布时间】:2014-05-19 16:44:02
【问题描述】:

我有一个在发送短信时调用的接收器。 当这种情况发生时,我想举杯。我知道向接收者展示敬酒不是一个好习惯,但我想知道为什么我的代码不起作用

public class SmsSentReceiver extends BroadcastReceiver
{

  @Override
  public void onReceive(Context context, Intent intent)
  {
    if (getResultCode() == Activity.RESULT_OK)
      Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
    else
      Toast.makeText(context, R.string.error_sending_sms, Toast.LENGTH_LONG).show();
    context.unregisterReceiver(this);
  }

}

接收者正确接收到事件,但没有显示任何 toast。 相反,如果我在调试模式下运行应用程序,其中一个 toast 会正确显示。

提前谢谢你。

【问题讨论】:

  • 你怎么知道它叫什么?
  • 因为我放了一个断点:)
  • 如果您使用上下文,那么它将仅显示给活动。但是广播接收器可以用于多个活动。
  • @Shriram 好的,但即使使用 context.getApplicationContext() 它也不起作用
  • 尝试 getBaseContext() 而不是 getApplicationContext()

标签: android broadcastreceiver android-toast


【解决方案1】:

试试这个

new Handler(Looper.getMainLooper()).post(new Runnable()
{
    @Override
    public void run()
    {
         Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
    }
});

【讨论】:

  • 也许您的应用设置中的“显示通知”设置已被选中?
  • 不,我确定。即使是因为当应用程序在调试模式下运行时会显示 toast :(
  • 在这种情况下,创建一个虚拟活动,该活动将显示祝酒词,然后立即结束。
【解决方案2】:

试试这个:

Context c;
...
...
....

Toast.makeText(c,"Succesfully Written",Toast.LENGTH_SHORT).show();

【讨论】:

    【解决方案3】:

    尝试关注

      public class SmsSentReceiver extends BroadcastReceiver
     {
      @Override
      public void onReceive(Context context, Intent intent)
      {
        if (getResultCode() == Activity.RESULT_OK)
          Toast.makeText(getApplicationContext(), R.string.sent, Toast.LENGTH_SHORT).show();
        else
          Toast.makeText(getApplicationContext(), R.string.error_sending_sms, Toast.LENGTH_LONG).show();
        context.unregisterReceiver(this);
      }
    
    }
    

    希望对你有所帮助...

    【讨论】:

    • 尝试 getBaseContext() 而不是 getApplicationContext()
    • 它不知道那个函数......既不是来自接收者也不是使用 context.getBaseContext()
    • 无需使用 context.getBaseContext() 只需使用 getBaseContext() 或 getApplicationContext(),如果可以的话...
    • BroadcastReceiver 没有这些功能。我必须使用上下文来调用 getApplicationContext() 并且它没有 getBaseContext()
    • 尝试动态创建一个类,扩展 BroadcastReceiver。你会看到 getBaseContext() 不存在
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多