Service is not stop in android. how to fixed issues

别来无恙 提交于 2019-12-03 21:59:31

Dear Attaullah use Periodic service. I had the same problem i solved like this. In my case this was the code.

Service Code:

public class PeriodicService extends Service {
         Context context;
        private MyTask task;


        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
            this.context = (MainActivity) MainActivity.context;
            RequestPackage p = new RequestPackage();
            p.setMethod("GET");
            p.setUri("http://192.168.137.1/new/connect.php");

            p.setParams("param1", "" + MainActivity.lastIndex);
            task = new MyTask(this);
            task.execute(p);
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            task = new MyTask(this);
            RequestPackage p = new RequestPackage();
            p.setMethod("GET");
            p.setUri("http://192.168.137.1/new/connect.php");
            p.setParams("param1", "" + MainActivity.lastIndex);
            task.execute(p);
            return START_NOT_STICKY;

        }

        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            Intent ishintent = new Intent(this, PeriodicService.class);
            PendingIntent pintent = PendingIntent.getService(this, 0, ishintent, 0);
            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarm.cancel(pintent);
            alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                    30000, pintent);
        }

    }

Start and stop your service

Call stop service method after start service. As according to the life cycle of the service the destroy method is called when the service is stopped. After stopping the service pending intent is used where the service is delayed for some time according to your choice.

Intent intent = new Intent(
                "com.urdo.news.updates.latest.service.PeriodicService");
        MainActivity.this.startService(intent);
        stopService(intent);

MyTask Class

 public class MyTask extends AsyncTask<RequestPackage, String, List<Flower>> {
        Context context;
        private ArrayList<MyTask> tasks;
        List<Flower> flowerList;
        LazyImageLoadAdapter adapter;
        ProgressBar bar;
        NewLocalDb db;

        public MyTask(Context context) {
            this.context = context;
            tasks = new ArrayList<>();
            db = new NewLocalDb(context);

        }

        @Override
        protected void onPreExecute() {

            tasks.add(this);
        }

        @Override
        protected List<Flower> doInBackground(RequestPackage... params) {

            String content = HttpManager.getData(params[0]);

            if (content.trim().length() == 4) {
                return null;

            } else {
                flowerList = FlowerJSONParser.parseFeed(content);

                if (flowerList.size() > 0) {
                    for (int i = 0; i < flowerList.size(); i++) {

                        Flower flower = new Flower();
                        flower = flowerList.get(i);
                        int id = flower.getProductId();
                        String title = flower.getHealine();
                        String des = flower.getDetail();
                        String imageName = flower.getPhoto();
                        try {
                            if (db.isValueAvailable(id) > 0) {
                                Log.d("Valuexist", "value eixst");

                            } else {
                                db.addNews(id, title, des, imageName);
                                Log.d("TAG", imageName);

                            }
                        } catch (SQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Log.d("ERRor", e.getMessage().toString());
                        }
                    }
                } else {
                    return null;
                }
                flowerList = db.getAllNews();
                db.close();
            }
            Log.d("EEEEEE", "" + content.trim().length());

            return flowerList;
        }

        @SuppressWarnings("unused")
        @Override
        protected void onPostExecute(List<Flower> result) {

            tasks.remove(this);


            if (result == null) {
                Toast.makeText(context, "Web service not available",
                        Toast.LENGTH_LONG).show();

                return;
            }

            flowerList = result;

            if (result != null) {
                // add in data base
                updateDisplay();
            }

        }

        protected void updateDisplay() {

            adapter = new LazyImageLoadAdapter(context, flowerList);

            MainActivity.list.setAdapter(adapter);
            MainActivity.lastIndex = MainActivity.list.getAdapter().getCount();
            Toast.makeText(context, "" + MainActivity.lastIndex, 500).show();


        }
    }
M D

but service it does not stop.

Because you have return

 return START_STICKY;

in onStartCommand(...)

read more at START_STICKY and START_NOT_STICKY

and Official docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!