[英]Call method in MainActivity from BroadcastReceiver - Android
I want to call method in Main Activity from Broadcast Receiver. 我想从广播接收器调用主要活动中的方法。 This is my MainActivity
这是我的MainActivity
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void DisplayConn(){
if(isNetworkStatusAvailable(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "internet is available", Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error");
builder.setMessage("No Network Connection").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
And this is my BroadcastReceiver 这是我的BroadcastReceiver
public class ConnectionReceiver extends BroadcastReceiver {
public ConnectionReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
MainActivity myAct = new MainActivity();
myAct.DisplayConn();
}
}
So, everytime my Broadcast have receive it will call the methods in my MainActivity. 因此,每次我的广播都收到它,它将调用我的MainActivity中的方法。 Thanks in Advance.
提前致谢。
You can use LocalBroadcast Manager for sending a local broadcast from your ConnectionReceiver
. 您可以使用LocalBroadcast Manager从
ConnectionReceiver
发送本地广播。 In the MainActivity
you can register your receiver to receive local broadcasts. 在
MainActivity
您可以注册接收器以接收本地广播。 You can send a local broadcast when onReceive
is called, which will be received by your Activity. 您可以在调用
onReceive
时发送本地广播,您的活动将收到该广播。 Then in your activity you can call the method when you receive this local broadcast. 然后在您的活动中,您可以在收到本地广播时调用该方法。 This broadcast is only local to your app.
此广播仅适用于您的应用。 So is safe as well.
所以也是安全的。 You can see here how to use it: how to use LocalBroadcastManager?
你可以在这里看到如何使用它: 如何使用LocalBroadcastManager? .
。
LocalBroadcastManager is a helper to register for and send broadcasts of Intents to local objects within your process.
LocalBroadcastManager是一个帮助程序,用于注册和发送Intent广播到进程中的本地对象。 This is has a number of advantages over sending global broadcasts with sendBroadcast(Intent).
与使用sendBroadcast(Intent)发送全局广播相比,这有许多优点。 One of them is that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
其中之一是您播放的数据不会离开您的应用,因此不必担心泄露私人数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.