Kkk.
Kkk.

Reputation: 1

Java android intent service works only one time

I want to create a intent service which work all the time in whole application (in all activity ) with time period and do it task. I use a Handler . I started a service in activity . I see that only one time a service work (do it task) why ? This is my service :

public class SenderXML extends Service {

    public static boolean running = false;
    private Timer timer = new Timer();
    private SendXMLTask sendXMLTask;
    private Context context;

    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        Gson gson = new Gson();
        MainActivity.xmlList = null;
        MainActivity.xmlList = new ArrayList<>();
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
        List<String> productFromShared1 = new ArrayList<>();
        String jsonPreferences1 = sharedPref.getString("TAG1", "");

        Type type1 = new TypeToken<List<String>>() {
        }.getType();
        productFromShared1 = gson.fromJson(jsonPreferences1, type1);
        if (productFromShared1 != null)
            MainActivity.xmlList.addAll(productFromShared1);
        Log.e("tworzenie serwisu ", "tworzenie");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Dziełanie serwisu ", "Dziełanie");
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                Log.e("Dziełanie serwisu 1111", "Dziełanie 111");
                if (!MainActivity.xmlList.isEmpty()) {
                    if (NetworkUtil.isNetworkAvailable(context)) {
                        if (!running) {
                            sendXMLTask = new SendXMLTask();
                            sendXMLTask.execute();
                        }
                    }
                }
            }
        }, 1000 * 60 * 2);

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (running) {
            timer.cancel();
            sendXMLTask = new SendXMLTask();
            sendXMLTask.cancel(true);
            running = false;
        }
        Log.e("service ", "nie działa");
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

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

        @Override
        protected String doInBackground(Void... voids) {
            Log.e("xml ", MainActivity.xmlList.size() +"");
            running = true;
            HttpClient httpclient = HttpClientUtil.getHttpClient(getApplicationContext());
            HttpPost httppost = new HttpPost(Util.getServerUrl(getApplicationContext()) + "/SetData");
            ArrayList<NameValuePair> namevaluepairs = new ArrayList<>(2);
            namevaluepairs.add(new BasicNameValuePair("token", String.valueOf(E_Gps.TOKEN)));
            namevaluepairs.add(new BasicNameValuePair("xml", MainActivity.xmlList.get(0)));
            if (MainActivity.xmlList.size() > 0) {
                MainActivity.btTransfer.setBackgroundColor(Color.YELLOW);
            }
            try {
                httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpResponse response = null;
            try {
                response = httpclient.execute(httppost);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            InputStream responseInputStream = null;
            try {
                responseInputStream = new BufferedInputStream(response.getEntity().getContent());
                try {
                    int tt = ResponseParser.getResponseType(responseInputStream);
                    if (tt == 0) {
                        return null;
                    }
                } catch (EmptyResponseException | UnknownAnswerName | XmlPullParserException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("xml", MainActivity.xmlList.get(0));
            Log.e("xml wys ", convertStreamToString(responseInputStream));
            return convertStreamToString(responseInputStream);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {
                MainActivity.xmlList.remove(0);
                Gson gson = new Gson();
                String jsonCurProduct = gson.toJson(MainActivity.xmlList);
                SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("TAG1", jsonCurProduct);
                editor.apply();
            }
            if (!MainActivity.xmlList.isEmpty()) {
                sendXMLTask = new SendXMLTask();
                sendXMLTask.execute();
            } else {
                MainActivity.btTransfer.setBackgroundColor(Color.GREEN);
            }
            running = false;
        }
    }
}

Upvotes: 0

Views: 748

Answers (2)

David Wasser
David Wasser

Reputation: 95626

When you call startService() in your Activity, the Service is created (if it doesn't already exist) and onStartCommand() is called. onStartCommand() will not be called again unless you call startService() again.

Since you are posting a Runnable in onStartCommand(), you should just have your Runnable repost itself to run after a certain period of time (if you want this to run continuously).

Make sure that you stop your Service when you are done with it.

Upvotes: 1

Dhananjay Sarsonia
Dhananjay Sarsonia

Reputation: 144

Have you tried using Alarm Manager to start your Intent service periodically? If you have not tried you can follow this link for Alarm Manager Example

You can start your Intent Service periodically with Alarm Manager.

Upvotes: 1

Related Questions