从BroadcastReceiver调用MainApplication方法

时间:2015-07-08 13:13:13

标签: java android android-intent android-service

我有一个带有Activity,服务和广播接收器的Android应用程序。从服务中我称之为广播意图。广播接收器正确接收意图。

但是如何从我的班级MainApplication访问班级MyBroadcastReceiver的方法?

((MainApplication)getApplication()).myMethod();提供错误消息"无法解析方法"

//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(){

    }

}

祝你好运

3 个答案:

答案 0 :(得分:2)

将上下文转换为活动:

//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();
    }
}

答案 1 :(得分:1)

如果您未在AndroidManifest.xml中宣布application课程,则通常会发生上述情况。

在AndroidManifest.xml文件中找到MainApplication标记,并确保其名称属性指向您的<application android:name="com.you.package.MainApplication" - 如下所示。

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}

protected void onPause()
{
    super.onPause();
}

protected void onDestroy()
{
    super.onDestroy();
}

答案 2 :(得分:0)

动态创建BroadcastReceiver:

在您的BroadcastReceiver类中定义类成员:

YourMainActivity yourMain = null;

和方法:

setMainActivityHandler(YourMainActivity main){
yourMain = main;
} 
来自您的MainActivity的

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

当你的.BR.onReceive被解雇时,你可以打电话:

yourMain.methodOfMainActivity();