如何在任何Activity
中获取后台进程的结果?
我正在使用OTA更新。应用程序在后台与处理程序一起处理。更新完成后,我必须向用户显示警报对话框。我可以在以OTA开头的SettingsActivity
中显示它,但用户可以在任何其他Activity
中。
private void checkIsUpdated() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mDevice.getDevice().read(GattUUID.LS_DEVICE_INFORMATION, GattUUID.LC_FIRMWARE, new
BleDevice.ReadWriteListener() {
@Override
public void onEvent(ReadWriteEvent e) {
if (e.wasSuccess()) {
if (firmwareVersion.equals(e.data_string())) {
showAlertDialog("OTA update failed", "Device is not updated");
} else {
showAlertDialog("OTA update is successful.\nDevice is updated to new " +
"firmware!", "Device is updated");
}
Log.i("OTA", "Read firmware is new success");
} else {
Log.e("OTA", "Read firmware is new success");
}
}
});
}
}, 30000);
}
AlertDialog
代码 private void showAlertDialog(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.SwipeDialogLight);
builder.setTitle(title)
.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
if (!alert.isShowing()) {
alert.show();
}
}
最佳答案
正如@ W4R10CK所说,我也这么认为。 BroadcastReceiver
可能不是一个好主意。但是后来,我对它进行了思考,如果您在checkIsUpdated
中调用Service
函数并从中发送Broadcast
,这可能是一个可行的解决方案。
因此,基本上,您需要一个BaseActivity
类,并且其中需要一个BroadcastReceiver
。您需要注册onResume
,然后再次取消注册onPause
。
而且您还需要在每个abstract
中都覆盖一个Activity
方法。
因此,您的BaseActivity
可能看起来像这样。
public abstract class BaseActivity extends AppCompatActivity {
private final Context context;
public BaseActivity() {
this.context = setContext();
}
protected abstract Context setContext();
@Override
public void onResume() {
super.onResume();
registerBroadcastReceiver();
}
@Override
public void onPause() {
super.onPause();
unRegisterBroadcastReceiver();
}
// Declare your BroadcastReceiver here
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
showAlertDialog(context);
}
}
}