gpt4 book ai didi

java - 从 BroadcastReceiver 调用 MainApplication 方法

转载 作者:行者123 更新时间:2023-12-01 22:14:47 25 4
gpt4 key购买 nike

我有一个带有 Activity、服务和广播接收器的 Android 应用程序。我从服务中调用了一个有效的广播 Intent 。广播接收器正确接收 Intent 。

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

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

}

}

致以诚挚的问候

最佳答案

将上下文转换为 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();
}
}

关于java - 从 BroadcastReceiver 调用 MainApplication 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31293789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com