0
votes

I am developing an application which connects to a web service via the internet and gets some information and I've used Async task for this in two activities. Now I want to use the same code in a service class which works with Timer task and on every tick, if the application is not running, it should return some data from web service. I can retrieve data when the app is open, but when I close it, I get "Connection to foo.com is refused"!

I have uses-permission android:name="android.permission.INTERNET" in my Android manifest.

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;

}

I get the error on this line ==> HttpResponse response = httpClient.execute(httppost);

1

1 Answers

0
votes

Android have some restrictions with background service in new OS versions I got the same issue and tried running service with notification and it worked. for ex:

   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());

}

This is a sample notification that is triggered from a service class oncreate() just before initiating service.This will make the service active even if app goes background