在 Android 中从 BroadcastReceiver 调用 Activity 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22241705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a Activity method from BroadcastReceiver in Android
提问by Jay Vyas
Here I am creating an online application that depends only on Internet.
在这里,我正在创建一个仅依赖于 Internet 的在线应用程序。
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).
因此,每当出现网络错误时,它必须通知用户。为此,我创建了一个 BroadcastReciver,它在网络连接丢失(互联网)时接收呼叫。
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.
所有这一切都完美无缺。现在我需要的是我必须从这个广播接收器调用一个 Activity 方法,我在那里创建了一个警报对话。
I have read many answers on stack-overflow.com that I can declare that method static and call by using only Activity name,
我在 stack-overflow.com 上阅读了许多答案,我可以声明该方法为静态并仅使用活动名称进行调用,
e.g MyActivityName.myMethod()
例如 MyActivityName.myMethod()
But I can't declare my method static, because I am using Alert Dialogue there and it shows me error on line,
但是我不能声明我的方法是静态的,因为我在那里使用了 Alert Dialogue 并且它在线显示了我的错误,
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
that Cannot use this in a static context.
即不能在静态的环境中使用此。
So, how can I call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?
那么,如何从广播接收器调用 Activity 的方法(不能是静态的并且不启动该活动)?
And can I get Activity(or fragment) name from Broadcast Receiver which is currently running?
我可以从当前正在运行的广播接收器中获取活动(或片段)名称吗?
回答by Vijju
try this code :
试试这个代码:
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);
}
}
回答by Vijju
Add a boolean variable in you activity from where you are open alertdialog
从您打开警报对话框的位置在您的活动中添加一个布尔变量
boolean isDialogOpened = false;
// in broadcast recever check
if(isDialogOpened) {
alertDialog();
}
And replace your code for alertdialog with this one
并用这个替换你的 alertdialog 代码
public void alertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("Network not found.");
alertDialog.setPositiveButton("Check Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
isDialogOpened = false;
}
});
alertDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
isDialogOpened = false;
}
});
alertDialog.show();
}
回答by Rohit Singh
INTERFACE: Keep BroadCastReceiver and Activity code separate!
接口:将 BroadCastReceiver 和 Activity 代码分开!
You can make a CallBackListener interface. The interface will work as a bridge between BroadcastReceiver
and Activity
.
您可以创建一个 CallBackListener 接口。该接口将作为BroadcastReceiver
和之间的桥梁Activity
。
1) Create a CallbackListener
1)创建一个回调监听器
interface ConnectionLostCallback{
public void connectionLost();
}
2) Provide ConnectionLostCallback
in your BroadcastReceiver
2)ConnectionLostCallback
在您的 BroadcastReceiver 中提供
public class MyBroadcastReceiver extends BroadcastReceiver{
private ConnectionLostCallback listener;
public MyBroadcastReceiver(ConnectionLostCallback listener ){
this.listener = listener //<-- Initialze it
}
@Override
public void onReceive(Context context, Intent intent) {
listener.connectionLost();
}
}
3) Implement the ConnectionLostCallback
in your Activity and override the method
3)ConnectionLostCallback
在您的活动中实现并覆盖该方法
YourActvity extends AppcompatActivity implements ConnectionLostCallback{
// Your Activity related code //
// new MyBroadcastReceiver(this); <-- create instance
private void showAlertMessage(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
}
@Override
public void connectionLost(){
showAlertMessage(); //<--- Call the method to shoe alert dialog
}
}
Relevant link:
相关链接:
If you want to know how to make a BroadcastReceiver independent of any activity ie How can you reuse the same BroadCastReceiver with different Activities? Then READ THIS
如果您想知道如何使 BroadcastReceiver 独立于任何活动,即如何将相同的 BroadCastReceiver 与不同的活动重用?然后阅读这个
回答by junhaotee
Pass your Activity's context to BroadcastReceiver's contructor.
将您的 Activity 上下文传递给 BroadcastReceiver 的构造函数。
public class ResponseReceiver extends BroadcastReceiver{
MainActivity ma; //a reference to activity's context
public ResponseReceiver(MainActivity maContext){
ma=maContext;
}
@Override
public void onReceive(Context context, Intent intent) {
ma.brCallback("your string"); //calling activity method
}
}
and in your MainActivity
并在您的 MainActivity
public class MainActivity extends AppCompatActivity {
...
public void onStart(){
...
ResponseReceiver responseReceiver = new ResponseReceiver(this); //passing context
LocalBroadcastManager.getInstance(this).registerReceiver(responseReceiver,null);
...
}
public void brCallback(String param){
Log.d("BroadcastReceiver",param);
}
}
hope it helps
希望能帮助到你
回答by Adeel Ahmad
Same as Vijju' s answer but using Local Broadcasts instead
与 Vijju 的回答相同,但使用本地广播代替
public class SampleReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent intentToBroadcast = new Intent("YOUR_ACTION_HERE");
LocalBroadcastManager.getInstance(context).sendBroadcast(intentToBroadcast);
}
}
In your activity add this
在您的活动中添加这个
public class SampleActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mSampleReceiver, new IntentFilter(YOUR_ACTION_HERE));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mSampleReceiver);
super.onPause();
}
private SampleReceiver mSampleReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// your code here
}
};
}
NoteMove the register/unregister calls to onCreate/onDestroy is you want to be notified even when your activity is in the background.
注意将注册/取消注册调用移动到 onCreate/onDestroy 是您希望即使在您的活动在后台时也能收到通知。