1.在Android接收者类中,onReceive()方法并不能直接用findById方法进行UI刷新,此时我们就需要在接收者中找到MainActivity所对应的Activity,利用这个Activity来进行UI的刷新。
2.实例代码(就拿Android获取电源状况的代码来说)
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
String batteryState="电池状态";
switch (intent.getAction())
{
case "android.intent.action.BATTERY_LOW":batteryState="当前电池点量过低!即将自动关机";break;
case "android.intent.action.BATTERY_OKEY":batteryState="当前电池点量正常";break;
case "android.intent.action.ACTION_POWER_CONNECTED":batteryState="当前电池正在充电"; break;
case "android.intent.action.ACTION_POWER_DISCONNECTED":batteryState="当前电池充电断开"; break;
}
Toast.makeText(context,batteryState,Toast.LENGTH_LONG).show();
}
//在onReceive()未查询修改代码状态的语句时
修改后,可以进行UI界面更新的代码如下
private Activity activity;
private MainActivity mainActivity;
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
String batteryState="电池状态";
switch (intent.getAction())
{
case "android.intent.action.BATTERY_LOW":batteryState="当前电池点量过低!即将自动关机";break;
case "android.intent.action.BATTERY_OKEY":batteryState="当前电池点量正常";break;
case "android.intent.action.ACTION_POWER_CONNECTED":batteryState="当前电池正在充电"; break;
case "android.intent.action.ACTION_POWER_DISCONNECTED":batteryState="当前电池充电断开"; break;
}
TextView textView=mainActivity.findViewById(R.id.textView);
textView.setText(batteryState);
Toast.makeText(context,batteryState,Toast.LENGTH_LONG).show();
}
public void SetActivity(Activity activity) //此处新写方法,用来获取Activity
{
this.mainActivity=(MainActivity) activity; //将传入的activity强转未MainActivity
}
之后只需在MaintActivity中调用SetActivity()方法传入Activity即刷新UI界面的状态