簡體   English   中英

服務不會在android中停止。 如何解決問題

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

我從android活動startservice(intent);啟動服務startservice(intent); stopservice(intent);

當我要求停止服務但服務並未停止時,我的服務類實際上包含LocationListener,它獲取緯度和經度,然后存儲在sqlite中,並將此類信息發送到服務器。

另一個問題是LocationUpdate方法會在第二秒后自動調用

如何延長時間,例如30秒

如何停止服務以停止LocationListener並將值存儲在sqlite服務器中。

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

            }
        });



}

但是服務不會停止。

因為你有回報

 return START_STICKY;

onStartCommand(...)

START_STICKY和START_NOT_STICKY上了解更多

官方文檔

尊敬的Attaullah使用定期服務。 我有同樣的問題,我這樣解決。 就我而言,這就是代碼。

服務代碼:

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

    }

啟動和停止您的服務

啟動服務后調用停止服務方法。 根據服務的生命周期,當服務停止時會調用destroy方法。 停止服務后,將使用掛起的意圖,根據您的選擇,該服務會延遲一段時間。

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

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