简体   繁体   中英

Service is not stop in android. how to fixed issues

I start service from an android activity startservice(intent); stopservice(intent);

When i call for stopping service but service it does not stop actually my service class contains LocationListener that get latitude and longitude and then store in sqlite and also sent such information into server.

Another issue is LocationUpdate method is automatically call after second

How to extend time eg 30 second

How to stop service to stop LocationListener and storing value in sqlite server.

UpdateServices.java

public class UpdateServices extends Service implements LocationListener {

    String id, latee, longee;
    // j
    private ProgressDialog pDialog;
    ProgressDialog progressDialog;
    JSONParser jsonParser = new JSONParser();
    DBManager db;
    private static String url_create_locationupdate = "http://192.168.0.175/simple_demo3/classes/create_locationupdate.php";
    private static final String TAG_SUCCESS = "success";
    public static String LOG = "Log";
    private final Context mContext;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 3; // 0 meters
    private long MIN_TIME_BW_UPDATES; // 10 second
    private long MIN_LENGTH_BW_UPDATES;
    SharedPreferences mPref;
    protected LocationManager locationManager;

    public UpdateServices(Context context) {
        this.mContext = context;
    }

    public UpdateServices() {
        super();
        mContext = UpdateServices.this;
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
        Log.i(LOG, "Service started");

        mPref = getSharedPreferences("mFile", 0);
        MIN_TIME_BW_UPDATES = mPref.getLong("mint", 1) * 1000 * 60;
        MIN_LENGTH_BW_UPDATES = mPref.getLong("kmeter", 1) * 1000;
        Log.i("asd", "This is sparta");
        latitude = getLocation().getLatitude();
        longitude = getLocation().getLongitude();

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(LOG, "Service created");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG, "Service destroyed");

    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, 5000,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    @Override
    public void onLocationChanged(Location location) {
        // this will be called every second
        String laty = Double.toString(getLocation().getLatitude());
        String lagy = Double.toString(getLocation().getLongitude());
        db = new DBManager(mContext);
        db.open();
        db.mInsertGPSCor(laty, lagy);
        Toast.makeText(
                getApplicationContext(),
                "Your Location is - \nLat: " + location.getLatitude()
                        + "\nLong: " + location.getLongitude(),
                Toast.LENGTH_LONG).show();

        Toast.makeText(UpdateServices.this, "record entered",
                Toast.LENGTH_SHORT).show();
        db.close();
// store in server
        new CreateNewProduct(this).execute();

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    class CreateNewProduct extends AsyncTask<String, String, String> {
        private Context mContext;

        public CreateNewProduct(Context context) {
            super();
            mContext = context;
        }

        @Override
        protected void onPreExecute() {
            try {
                super.onPreExecute();
                progressDialog = ProgressDialog.show(mContext,
                        "Press Back to Cancel", "Sending Data to Server..",
                        true, false);
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("ID", id));
            params.add(new BasicNameValuePair("LATITUDE", latee));
            params.add(new BasicNameValuePair("LONGITUDE", longee));

            JSONObject json = jsonParser.makeHttpRequest(
                    url_create_locationupdate, "POST", params);

            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    return "done";
                } else {
                    // failed to create product
                    return "fail";
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return "exec";
            }

        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();

            if (file_url.equalsIgnoreCase("done")) {

                show.message(mContext, "uploading successed");
            }
            if (file_url.equalsIgnoreCase("fail")
                    || file_url.equalsIgnoreCase("exec")) {
                try {
                    show.message(mContext, "uploading failed");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub

    }

}

Main.java

public class Main extends Activity {

    Button btn_startGps, btn_stopGps;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auto_gps_update);
        btn_startGps = (Button) findViewById(R.id.button_service);
        btn_stopGps = (Button) findViewById(R.id.button_stopservice);


        btn_startGps.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {           
                startService(new Intent(About.this, UpdateServices.class));
                Toast.makeText(About.this, "Service Started",
                        Toast.LENGTH_SHORT).show();
            }
        });

        btn_stopGps.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                stopService(new Intent(About.this, UpdateServices.class));
            Log.e("sss", "ddddd");
                Toast.makeText(About.this, "Service Stopped",
                        Toast.LENGTH_SHORT).show();

            }
        });



}

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

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


        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM