java - 我正在尝试从广播接收器发出 API 请求,有人能提到正确的方法吗?

标签 java android

公共(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/

相关文章:

java - 扫描仪分隔符获取由 ""和 "\n"java 分隔的标记

java - tomcat启动时,通常只允许每个套接字地址(协议(protocol)/网络地址/端口)使用一次?

android - 如何在android中的gridview滚动中保留复选框状态

java - 从 Android 通过套接字发送缓冲数据

java - 当手机屏幕锁定时,Android 计时器会延迟

android - TabLayout选项卡标题问题

java - 在 Java 中比较 double 值是否相等。

java - Ravendb 按值查询顺序

java - TreeMap 和 setValue 方法

android - android中Gson和Room的ID问题(发送json到客户端)