此问题与大多数“显示吐司”问题略有不同。我不是要求在其他活动中显示Toast消息,而是要查看后台服务在其他活动除主要活动时发送的Toast消息。我在主要活动中看到了Toast消息!
我有一个具有后台服务的应用程序。当在此后台服务中发生某些事件时,将显示Toast消息。后台服务从外部BT和BLE设备接收数据,并通过wifi发送消息。 Toast消息显示这些过程中的某些重要事件。 MainActivity
和后台服务使用getApplicationContext()
中的应用程序上下文来显示此Toast消息。
但是,如果我移动到另一个Activity
,则不会显示这些消息。例如,配置一些参数。我不是试图显示来自其他活动的祝酒词;我能做到的。但是,除了Activity
之外,当我在另一个MainActivity
时,如何从后台服务中获取Toast消息?我想我需要做一些事情,比如“在应用程序上下文中运行活动”,虽然我不知道如何做(或者即使有可能)。
答案 0 :(得分:1)
为此目的使用BroadcastReceiver
。在每个Activity
中,您需要声明BroadcastReceiver
这样的内容。
private class ShowToastBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("Message");
Toast.makeText(OtherActivity.this, message, Toast.LENGTH_LONG).show();
}
}
您需要每次在BroadcastReceiver
注册onResume
,并在活动的onPause
功能中取消注册。
// This is in your Activity
private ShowToastBroadcastReceiver showToastBroadcastReceiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showToastBroadcastReceiver = new ShowToastBroadcastReceiver();
}
@Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(showToastBroadcastReceiver, new IntentFilter("SHOW_TOAST"));
}
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(showToastBroadcastReceiver);
}
现在您需要从Service
发送广播,让吐司显示在Activity
中。
// This is in your Service
Intent intent = new Intent("SHOW_TOAST");
intent.putExtra("Message", "This toast needs to be shown");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
答案 1 :(得分:0)
您应该可以在任何上下文中显示Toast
,包括Service
。 Toast Notifications开发人员指南的示例代码说明了如何:
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
换句话说,您根本不需要Activity
。您可以直接从Toast
显示Service
。如果您担心从单独的线程执行此操作,请在Handler
的主线程中创建Service
并向该处理程序发布Runnable
或消息以显示{ {1}}。
另一种可能性是您正在使用绑定服务,当您从主要活动切换时它会消失。确保服务本身仍在运行。
哦,还要确保'显示通知'您的应用设置尚未取消选中。
答案 2 :(得分:0)
感谢Reaz我发现了一个愚蠢的错误。我在onStop()而不是onDestroy()上取消注册处理Toasts的BroadcastReceiver。将取消注册移动到onDestroy()并将注册和过滤器移动到onCreate()解决了这个问题。