简体   繁体   中英

Calling MainApplication methods from BroadcastReceiver

I have an Android Application with an Activity, a service and a Broadcast receiver. From the service I call a Broadcast Intent which works. The Broadcast Receiver receives the intent correctly.

But how can I access methods of the class MainApplication from my Class MyBroadcastReceiver ?

((MainApplication)getApplication()).myMethod(); gives the error-message "cannot resolve method"

//Call from the service-class
private void sendBroadcast() {
    Log.d(TAG, "Sending Broadcast Intent");
    Intent intent = new Intent();
    intent.setAction("com.package.name.MyBroadcastReceiver");
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    sendBroadcast(intent);
}


//receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Doesn't work - "cannot resolve method"
        ((MainApplication)getApplication()).myMethod();
        //Doesn't work either
        ((MainApplication)context.getApplication()).myMethod();
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    }
}



//Main Application Class
public class MainApplication extends Application{

    public void myMethod(){

    }

}

Best regards

Cast the context to an Activity:

//receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Activity activity = (Activity) context;
        ((MainApplication)activity.getApplication()).myMethod();
        Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
    }
}

The above usually happens if you haven't declared you MainApplication class in your AndroidManifest.xml .

Find the application tag in your AndroidManifest.xml file, and ensure it's name attribute points to your MainApplication - something like below.

<application
        android:name="com.you.package.MainApplication"

Create the BroadcastReceiver dynamically:

In your BroadcastReceiver class define class member:

YourMainActivity yourMain = null;

and method:

setMainActivityHandler(YourMainActivity main){
yourMain = main;
} 

from your MainActivity do:

private YourBroadcastReceiverClassName yourBR = null;
yourBR = new YourBroadcastReceiverClassName();
    yourBR.setMainActivityHandler(this);    
    IntentFilter callInterceptorIntentFilter = new           IntentFilter("android.intent.action.ANY_ACTION");
    registerReceiver(yourBR,  callInterceptorIntentFilter);

when yourBR.onReceive is fired you can call:

yourMain.methodOfMainActivity();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM