公共(public)类 GetReceiver 扩展了 BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
SharedPrefHelper sharedPrefHelper = new SharedPrefHelper(context);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(1);
if (intent != null) {
if (intent.getStringExtra("result") == "ok") {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty(Web.Register.User_Id, sharedPrefHelper.getUserId());
jsonObject.addProperty(Web.BookingRequest.ACTIVITY, "ok");
new BasePresenter<>().createApiRequest(BaseApplication.getRetrofit().create(ApisHelper.class)
.okResponse(jsonObject), new BaseCallBack<BasicApiModel>() {
@Override
public void onCallBack(BasicApiModel output) {
if (Log.isLoggable("qwert", Log.DEBUG)) {
Log.d("qwert", "Receiver's onCallBack: " + output.getMessage());
}
}
});
} else {
Log.d("qwert", "onReceive: testing_cancelled");
}
}
}
从接收者发起 api 请求的正确方法是什么?
最佳答案
不要在广播接收器中启动任何长时间运行的任务,否则如果 onReceive 运行超过 10 秒,您的应用可能会崩溃。 最好从 onReceive 方法触发服务并将网络操作放入该服务中。 另请记住,根据您的要求使用 Intent 服务/任何其他服务,并使用工作线程来运行网络操作,以便您的 UI 线程不会被阻塞。
关于java - 我正在尝试从广播接收器发出 API 请求,有人能提到正确的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61136160/