我需要在屏幕上显示连接状态。这似乎是一项简单的任务......
这是我的接收者代码:
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。任何人都可以帮忙吗?谢谢!
答案 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();
}
}