网络呼叫报警超时

jel*_*ief 8 networking android alarmmanager retrofit

我有一个应用程序,用于AlarmManager每隔X个时间安排重复警报.当我的接收器收到时Intent,它必须发出http请求.

警报本身工作正常,并在应有时启动.但是,网络呼叫在手机不使用时开始超时.更具体:

当我计划每分钟开火时(不好的做法,我知道,但只是为了说明),请求成功的前5-8分钟.在那之后,我得到了一个java.net.SocketTimeoutException: connect timed out.有时它确实成功了,但大多数情况都会发生.

我尝试将连接/读/写超时设置为一分钟,但后来我得到了这个异常而不是上面的异常:java.net.ConnectException: Failed to connect to myapp.example.com/123.45.67.89:80.

我的代码:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Consider mApi and myBody to be initialised and valid
        mApi.myPostRequest(myBody).enqueue(new Callback<Void> {

            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                //Does not get here
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                t.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过的事情:

  • 如前所述,增加超时
  • 获取WakeLockonReceive和释放它当调用完成(添加权限)

其他信息:

  • 警报是alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), interval, pendingIntent);从我的 设置中设置的 Activity.
  • 我正在使用Retrofit(2.1.0)进行网络通信,但你可能已经猜到了我的代码;)

关于如何在手机睡眠时使网络通话工作的任何想法?

Mar*_*rky 1

您的代码中有一个基本错误 - 您无法在广播接收器中发出请求(或任何长时间运行的操作) - 它会在大约 10 秒后终止,因此这可能是某些失败的原因。

您应该将请求逻辑移至服务 (IntentService),您将从广播接收器启动该服务并在那里发出请求。

那应该工作得很好。