[英]Send data from Broadcast receiver to MainActivity
I need to display status of connection on the screen. 我需要在屏幕上显示连接状态。 It seemed a simple task... 看起来很简单...
This is my receiver code below: 这是我下面的接收器代码:
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();
}
}
}
How can i display my STATE var on screen textView. 我如何在屏幕textView上显示我的状态变量。 Can anybody help with it? 有人可以帮忙吗? Thanks! 谢谢!
You need to register a Callback
. 您需要注册一个Callback
。 Create an Interface
in PowerConnectionReceiver
like: 在PowerConnectionReceiver
创建一个Interface
,如下所示:
public Interface NetworkStatusCallback {
public void onStateChange(String state);
}
Now implement this Callback
in your MainActivity
like: 现在在您的MainActivity
实现此Callback
,如下所示:
public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback {...}
Create a reference
of this Callback
in PowerConnectionReceiver
and declare it like: 在PowerConnectionReceiver
创建此Callback
的reference
,并进行如下声明:
private NetworkStatusCallback mCallback;
mCallBack = (NetworkStatusCallback)context;
Now in onReceive(Context context, Intent intent)
do this: 现在在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();
}
}
You will receive state in MainActivity
您将在MainActivity
收到状态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.