Reputation: 41
I am new to Android development and managed to get this far reading questions and answers on 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:
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?
Upvotes: 3
Views: 2626
Reputation: 1466
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:
public void onNewIntent (Intent intent) {
ligaInternet();
// This simply calls the function.
//so make sure the function is
//written somewhere inside
//MainActivity as well.
}
Upvotes: 0
Reputation: 321
try this. Dude, make the ligaInternet method static, only the static method can be referenced from class name. The statement MainActivity.ligaInternet() is now incorrect because ligaInternet() is a non static method hence it cannot be referenced from class name. and also remove the protected keyword from the method.
Upvotes: 0
Reputation: 13505
you can try
MainActivity currentActivity = ((MainActivity)context.getApplicationContext()).getCurrentActivity();
currentActivity.ligaInternet();
Upvotes: 1