在 Android 中从 BroadcastReceiver 调用 Activity 方法 [英] Calling a Activity method from BroadcastReceiver in Android
问题描述
这里我正在创建一个仅依赖于 Internet 的在线应用程序.
Here I am creating an online application that depends only on Internet.
所以每当出现网络错误时,它必须通知用户.为此,我创建了一个 BroadcastReciver,它可以在网络连接丢失(互联网)时接收呼叫.
So whenever there is a network error it must notify user. For that, I have created a BroadcastReciver that receives call when network connection gets lost(Internet).
所有这些都完美无缺.现在我需要的是我必须从这个广播接收器调用一个 Activity 方法,我在那里创建了一个警报对话.
All this works perfectly. Now what I need is that I have to call a method of Activity from this Broadcast Receiver, where I have created an Alert Dialogue.
我在 stack-overflow.com 上阅读了许多答案,我可以声明该方法为静态并仅使用活动名称进行调用,
I have read many answers on stack-overflow.com that I can declare that method static and call by using only Activity name,
例如 MyActivityName.myMethod()
但是我不能声明我的方法是静态的,因为我在那里使用 Alert Dialogue 并且它在线显示我的错误,
But I can't declare my method static, because I am using Alert Dialogue there and it shows me error on line,
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
不能在静态上下文中使用它.
那么,我如何从广播接收器调用 Activity 的方法(不能是静态的并且不启动该活动)?
So, how can I call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?
我可以从当前正在运行的广播接收器中获取活动(或片段)名称吗?
And can I get Activity(or fragment) name from Broadcast Receiver which is currently running?
推荐答案
试试这个代码:
您的广播接收器类用于互联网丢失类:
your broadcastreceiver class for internet lost class :
public class InternetLostReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}
在您的活动中添加此用于调用广播:
in your activity add this for calling broadcast:
public class TestActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// internet lost alert dialog method call from here...
}
};
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
}
这篇关于在 Android 中从 BroadcastReceiver 调用 Activity 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!