将数据从广播接收器发送到MainActivity

时间:2016-06-04 09:47:55

标签: android broadcastreceiver send

我需要在屏幕上显示连接状态。这似乎是一项简单的任务......

这是我的接收者代码:

public class PowerConnectionReceiver extends BroadcastReceiver {

public PowerConnectionReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}
}

如何在屏幕textView上显示我的STATE var。任何人都可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要注册Callback。在Interface中创建一个PowerConnectionReceiver,如:

public Interface NetworkStatusCallback {
    public void onStateChange(String state);
}

现在在Callback中实现此MainActivity,如:

public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback  {...}

reference中创建此Callback的{​​{1}},并声明如下:

PowerConnectionReceiver

现在在private NetworkStatusCallback mCallback; mCallBack = (NetworkStatusCallback)context; 执行此操作:

onReceive(Context context, Intent intent)

您将收到@Override public void onReceive(Context context, Intent intent) { String state; if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) { state = "Charging"; mCallback.onStateChange(state); Toast.makeText(context, state, Toast.LENGTH_SHORT).show(); } else { intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED); state = "Not charging"; mCallback.onStateChange(state); Toast.makeText(context, state, Toast.LENGTH_SHORT).show(); } }

中的州