简体   繁体   English

服务不会在android中停止。 如何解决问题

[英]Service is not stop in android. how to fixed issues

I start service from an android activity startservice(intent); 我从android活动startservice(intent);启动服务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. 当我要求停止服务但服务并未停止时,我的服务类实际上包含LocationListener,它获取纬度和经度,然后存储在sqlite中,并将此类信息发送到服务器。

Another issue is LocationUpdate method is automatically call after second 另一个问题是LocationUpdate方法会在第二秒后自动调用

How to extend time eg 30 second 如何延长时间,例如30秒

How to stop service to stop LocationListener and storing value in sqlite server. 如何停止服务以停止LocationListener并将值存储在sqlite服务器中。

UpdateServices.java 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 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(...) onStartCommand(...)

read more at START_STICKY and START_NOT_STICKY START_STICKY和START_NOT_STICKY上了解更多

and Official docs 官方文档

Dear Attaullah use Periodic service. 尊敬的Attaullah使用定期服务。 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. 根据服务的生命周期,当服务停止时会调用destroy方法。 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 MyTask类

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


        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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