[英]How to access MainActivity from broadcastReceiver callback
I am new to Android development and managed to get this far reading questions and answers on StackOverflow. 我是Android开发的新手,并设法在StackOverflow上获得了广泛的阅读问题和答案。 Thank you everyone. 谢谢大家。
I came up with a problem that I just can't figure out. 我想到了一个我无法解决的问题。 I have seen similar problems posted but the answers are not clear to me. 我已经看到过类似的问题,但是答案对我来说还不清楚。 Please help me on this one. 请帮我这个。
I want to call a method on my main activity from another class. 我想从另一个类的主要活动中调用一个方法。 The app crashes when I try to call the method. 当我尝试调用该方法时,应用程序崩溃。 Here is the code: 这是代码:
On the class file: 在类文件上:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity MainActivity = new MainActivity();
MainActivity.ligaInternet();
}
}
On the mainactivity file: 在mainactivity文件上:
protected void ligaInternet() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String urlText="http://www.regiprof.com/regiprof_sms.php";
String stringUrl = urlText.toString();
new DownloadWebpageTask().execute(stringUrl);
}
}
How can I call the ligaInternet()
function? 如何调用ligaInternet()
函数?
you can try 你可以试试
MainActivity currentActivity = ((MainActivity)context.getApplicationContext()).getCurrentActivity();
currentActivity.ligaInternet();
try this. 尝试这个。 Dude, make the ligaInternet method static, only the static method can be referenced from class name. 杜德(Dude),将ligaInternet方法设为静态,只能从类名中引用静态方法。 The statement MainActivity.ligaInternet() is now incorrect because ligaInternet() is a non static method hence it cannot be referenced from class name. 语句MainActivity.ligaInternet()现在不正确,因为ligaInternet()是非静态方法,因此无法从类名引用。 and also remove the protected keyword from the method. 并从方法中删除protected关键字。
Possible method. 可能的方法。 Put the following inside your broadcast receiver. 将以下内容放入广播接收器中。
Intent intent2open = new Intent(context, MainActivity.class)
And now inside MainActivity create a new method as follows: 现在在MainActivity内部创建一个新方法,如下所示:
public void onNewIntent (Intent intent) {
ligaInternet();
// This simply calls the function.
//so make sure the function is
//written somewhere inside
//MainActivity as well.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.