应用关闭后,Android服务无法连接到Web服务

时间:2019-01-15 08:21:12

标签: web-services android-studio service

我正在开发一个应用程序,该应用程序通过Internet连接到Web服务并获取一些信息,并且在两个活动中使用了异步任务。现在,我想在与Timer任务一起使用的服务类中使用相同的代码,并且在每个滴答滴答中,如果应用程序未运行,它应该从Web服务返回一些数据。当应用打开时,我可以检索数据,但是当我关闭应用时,我得到“拒绝连接到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响应= httpClient.execute(httppost);

1 个答案:

答案 0 :(得分:0)

Android在新OS版本中对后台服务有一些限制,我遇到了同样的问题,并尝试运行带有通知的服务,并且它可以正常工作。 例如:

   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()触发的。即使应用程序进入后台,这也会使服务处于活动状态