我有一个带有活动,服务和广播接收器的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(){
}
}
最好的祝福
最佳答案
将上下文转换为活动:
//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();
}
}