Служба Android не может подключиться к веб-службе, когда приложение закрыто - PullRequest
0 голосов
/ 15 января 2019

Я разрабатываю приложение, которое подключается к веб-службе через Интернет и получает некоторую информацию, и я использовал задачу Async для этого в двух действиях. Теперь я хочу использовать один и тот же код в классе обслуживания, который работает с задачей Timer, и на каждом тике, если приложение не запущено, оно должно возвращать некоторые данные из веб-службы. Я могу получить данные, когда приложение открыто, но когда я закрываю его, я получаю «Отказ в соединении с foo.com»!

В моем манифесте Android есть разрешение на использование android: name = "android.permission.INTERNET".

public void initializeTimerTask() {

    timerTask = new TimerTask() {
        public void run() {

            //use a handler to run a toast that shows the current timestamp
            handler.post(new Runnable() {
                public void run() {if(!isAppRunning(getApplicationContext(),getPackageName())) {

                            new ExecuteTask().execute();
                        }

                }
            });
        }
    };
}

class ExecuteTask extends AsyncTask<String, Void, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }


    @Override
    protected void onCancelled() {
        super.onCancelled();
    }


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

        String res1="";
        try {
                res1 = PostData();

        } catch (Exception ex) {
        }
        return res1;
    }


    @Override
    protected void onPostExecute(String result) {

        if (!isCancelled()) {
            Log.d("responsed", result);

            try {

                int Ifrom = result.indexOf("[");
                int ITo = result.lastIndexOf("]");
                if (Ifrom > -1 && ITo > -1) {
                    result = result.substring(Ifrom, ITo + 1);
                    Log.d("test", result);
                }

                android.util.JsonReader reader = new android.util.JsonReader(new StringReader(result));
                reader.setLenient(true);
                Type listType = new Type() {
                };

                listType = new TypeToken<List<Alarms>>() {
                }.getType();
                List<Alarms> lstAlarms = new ArrayList<Alarms>();
                lstAlarms = new Gson().fromJson(result, listType);

                //if there is new alarm then show notifications
                if(lstAlarms.size()>0)

            } catch (Exception ex)

            {
            }

        }

    }
}


public String PostData() {
    String s = "";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        String Url = "";
            Url = settingsWeb.getString("Address", null);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("JsonQuery",Command);
        Url += "/SelectJsonAlarms";


        HttpPost httppost = new HttpPost(Url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(httppost);

        s = readResponse(response);
    } catch (Exception e) {
        return "error";
    }

    return s;

}

Я получаю сообщение об ошибке в этой строке ==> HttpResponse response = httpClient.execute (httppost);

1 Ответ

0 голосов
/ 15 января 2019

Android имеет некоторые ограничения с фоновым сервисом в новых версиях ОС. У меня возникла та же проблема, и я попытался запустить сервис с уведомлением, и это сработало. Например:

   private void invokeForegroundNotification(String message) {
    int resId = 0;

    Intent intent = new Intent();
    NotificationChannel mChannel = null;
    Notification.Builder mBuilder = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mChannel = new NotificationChannel(NOTIFICATION_ID, getApplicationContext().getString(R.string.app_name), NotificationManager.IMPORTANCE_LOW);
        mBuilder = new Notification.Builder(getApplicationContext(), NOTIFICATION_ID);
    } else {
        mBuilder = new Notification.Builder(getApplicationContext());
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        notificationManager.createNotificationChannel(mChannel);
    }


    if (Build.VERSION.SDK_INT >= 19) {
        resId = R.drawable.icon;
    } else {
        resId = R.drawable.ic_launcher;
    }
     intent = new Intent();

    intent.setClassName(UtilConstants.PACKAGE_NAME, "com.test.ui.activities.Dashboard");
    intent.putExtra("activity", 0);
    if (message.equalsIgnoreCase(getApplicationContext().getResources().getString(R.string.detecting))) {
        intent.putExtra("detection_notification_click", 1);
        intent.setAction("detection_in_progress_clicked");
    } else {
        intent.putExtra("notification_click", 1);
      intent.setAction("notification_click");
    }
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(getApplicationContext(), 1,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );

    mBuilder
            .setContentText(message).setSmallIcon(resId)
            .setWhen(System.currentTimeMillis())
            .setContentIntent(resultPendingIntent);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        mBuilder.setColor(ContextCompat.getColor(this, R.color.blue));
    }

    mBuilder.setAutoCancel(true);
    startForeground(ServiceConstants.START_FOREGROUND_NOTIFICATION_ID, mBuilder.build());

}

Это пример уведомления, которое запускается из класса обслуживания oncreate () непосредственно перед запуском службы. Это сделает службу активной, даже если приложение переходит в фоновый режим

...