我的MainActivity类很大。因此,我想将内部类BroadcastListener分成普通类,但我面临的问题是,我不知道如何从此BroadcastReceiver类中访问MainActivity中的方法和变量。有没有办法做到这一点?
我感谢任何帮助。
private class BroadcastReceiverListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
// This method"deliverBestAccessPoint" is in MainActivity class
String a = deliverBestAccessPoint(updatedResults);
//I want to set the "textwifi" varaible in MainActivity
textWifi.setText(a.toString());
}
}
else if (intent.getAction().equals(
android.net.ConnectivityManager.CONNECTIVITY_ACTION)) {
}
}

答案 0 :(得分:2)
创建一个界面
interface ReceiverInteface
{
onBroadcastReceive();
}
让mainActivity实现此接口
mainactivity implements ReceiverInterface
{
@override
onBroadcastReceive()
{
//do all you task here
}
}
BroadCastReceiverListner Class
从Mainactiivty传递接口的参考。
ReceiverInteface recevierListner;
BroadcastReceiverListener(ReceiverInteface mListner)
{
recevierListner = mListner;
}
private class BroadcastReceiverListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
android.net.wifi.WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
recevierListner.onBroadcastReceive();
}
}
}