连接超时Android服务

时间:2018-07-19 18:36:08

标签: java android android-studio service httprequest

我正在使用Java在Android Studio中制作一个android应用,其功能是每天通过http请求获取我的工作时间表(我使用的是OkHttpClient)。

我对服务中的请求有疑问,当我发出由警报触发的请求时,我收到下一条消息=“连接超时”,并且该请求将不会启动。有趣的是,在具有API 21的Android中,请求可以正常工作,但是在具有API 24 Nugat的Android较新版本中,它不能正常工作,仅当我打开应用程序时,它才能工作设置我的闹钟的活动:

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 52);
    calendar.set(Calendar.SECOND, 0);

    Intent intent = new Intent(getApplicationContext(), ScheduleReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

我的接收器中的代码:

    Log.d("SCHEDULE-RECEIVER", "SCHEDULE");

    Intent i = new Intent("schedules_update");
    context.sendBroadcast(i);

为我服务:

   public void onCreate() {
    super.onCreate();


    if(broadcastReceiverSchedules == null) {
        broadcastReceiverSchedules = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("-->[SERVICE]", "Schedules");
                getUserSchedule(context);
            }
        };
    }

    registerReceiver(broadcastReceiverSchedules, new IntentFilter("schedules_update"));
}

在方法调用getUserSchedule中,我从SQLite数据库获取用户ID,并将其发送到http请求方法:

 public void getUserSchedule(Context context){

    contextLocal = context;

    ConnectionSQLiteHelper conn = new ConnectionSQLiteHelper(contextLocal, "cloe_users", null, 1);

    SQLiteDatabase db = conn.getReadableDatabase();
    String[] fields = {Utilities.TOKEN, Utilities.USER_ID};

    try {

        Cursor cursor = db.query(Utilities.TABLE_NAME, fields, Utilities.ID + "=?", new String[]{"1"}, null, null, null);
        cursor.moveToFirst();

        token   = cursor.getString( cursor.getColumnIndex("token"));
        user_id = cursor.getString( cursor.getColumnIndex("user_id"));
        cursor.close();

        if(user_id != "") {
            HttpRequestSchedules httpRequestSchedules = new HttpRequestSchedules();
            httpRequestSchedules.execute();
        }
        else
        {
            showErrorNotification("REG", "User couldn't be found");
        }
    } catch( Exception e) {

        Log.d("[SQL SERVICE]", "Error: " + e.getMessage());
        showErrorNotification("REG", "Error: " + e.getMessage());
    }

}

我的httpRequest方法:

 private class HttpRequestSchedules extends AsyncTask<String, Void, String> {

    private boolean successRequest = false;

    @Override
    protected String doInBackground(String... strings) {

        try {

            Log.d("[SCHEDULES]", "Petición horarios");

            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(URL_SERVER + "/api/users/"+ user_id + "/schedules")
                    .header("Authorization", "Bearer "+ token)
                    .build();

            Response response = client.newCall(request).execute();

            JSONObject dataObject = new JSONObject(response.body().string());

            Log.d("Request schedule", dataObject.toString());

            String data =  dataObject.getString("data");
            JSONArray jsonArray = new JSONArray(data);

            if(jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject hourMin = new JSONObject(jsonArray.getString(i));

                    String hour = hourMin.getString("hour");
                    String min = hourMin.getString("minute");

                    Boolean insertedCorrectly =  setAlarm(hour, min, i);

                    if(insertedCorrectly) {
                        Log.d("[SCHEDULE] HOUR", hour);
                        Log.d("[SHEDULE] MIN", min);
                    }
                    else
                    {
                        Log.d("[SHEDULE] ALARM", "Alarm not setted");
                    }
                }
            }

            successRequest = true;

            return "Success: " + data;

        } catch( Exception e) {

            return e.getMessage();
        }
    }

    @Override
    protected void onPostExecute(String s) {

        Log.d("[SCHEDULES] on Post", s);
    }
}

我是Android和Java的初学者,我没有经验,也不知道自己做错了什么。

谢谢。

0 个答案:

没有答案