如何在任何 Activity
中获取后台进程的结果?
我正在使用 OTA 更新。应用程序在后台使用处理程序处理它。更新完成后,我必须向用户显示警报对话框。我可以在 SettingsActivity
中显示它,我从 OTA 开始,但用户可以在任何其他 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
可能不是一个好主意。但后来,我考虑了一下,如果你在 Service
中调用 checkIsUpdated
函数并从中发送 Broadcast
,它可能是一个可行的解决方案。
所以基本上您需要一个 BaseActivity
类,并且在其中您需要一个 BroadcastReceiver
。您需要在 onResume
上注册它并再次在 onPause
上注销它。
而且您还需要在每个 Activity
中覆盖一个 abstract
方法。
所以你的 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);
}
}
}
关于java - 在任何 Activity 中显示来自后台进程的警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523291/