跟踪服务并没有停止android

时间:2016-01-18 18:16:05

标签: android service tracking

我创建了一个应用,用户可以在按下开始按钮并暂停跟踪暂停按钮并停止跟踪停止按钮时跟踪路线。

在我的代码跟踪工作正常但当我点击暂停按钮或停止按钮跟踪似乎没有停止。

我还通过在服务中的onDestroy方法中添加Toast进行检查。它被称为服务仍未停止。

它继续在地图上绘制路径并不断更新距离

以下是我的跟踪活动:

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import bytesizebit.com.networklibrariestest.R;

public class HomeScreen extends BaseActivity {
    int dday, dmonth, dyear;
    GoogleMap googleMap;
    Button btn_location, btn_start, img_select_sport, btn_pause, btn_scheduler;
    LinearLayout lyt_text;
    TextView tv_distance, tv_title_actionbar, tv_status, tv_speed;
    RelativeLayout lyt_status;
    Chronometer timer;
    ImageButton img_nav_actionbar;
    int flag, stoppedtime = 0;
    long time_stop = 0, timeWhenStopped, currentTime, timeElapsed;
    String action = "com.example.googlemapreciever.location", format_value, format_value1;
    LocationReciever mReceiver;
    MapSharedPref mapTrack;
    GPSTracker gps;
    boolean stopVar = false;
    boolean doubleBackToExitPressedOnce = false;
    boolean pp = true;

    private static final String FORMAT = "%02d:%02d:%02d";
    public static long diff1 = 1000;
    int mYear, mMonth, mDay, mMinute, mHour; // selected date time
    int Hour, Minute, hourDiff, minDiff, cday, cmonth, cyear; // current time
    EditText et_date, et_time;
    long ltt, diff2, Mltt;

    private class LocationReciever extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent service) {
            animateCameraTo();
            Toast.makeText(getApplicationContext(), "Inside locationReciever", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentView(R.layout.home_screen);
        // setContentView(R.layout.home_screen);
        gps = new GPSTracker(HomeScreen.this);
        mapTrack = new MapSharedPref(HomeScreen.this);
        lyt_text = (LinearLayout) findViewById(R.id.lyt_text);
        lyt_status = (RelativeLayout) findViewById(R.id.lyt_status);
        btn_start = (Button) findViewById(R.id.btn_start);
        tv_status = (TextView) findViewById(R.id.tv_status);
        img_nav_actionbar = (ImageButton) findViewById(R.id.img_nav_actionbar);
        tv_title_actionbar = (TextView) findViewById(R.id.tv_title_actionbar);
        tv_distance = (TextView) findViewById(R.id.tv_distance);
        img_select_sport = (Button) findViewById(R.id.img_select_sport);
        tv_speed = (TextView) findViewById(R.id.tv_speed);
        btn_location = (Button) findViewById(R.id.btn_location);
        timer = (Chronometer) findViewById(R.id.chronometer_time);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        img_nav_actionbar.setVisibility(View.VISIBLE);
        btn_scheduler = (Button) findViewById(R.id.btn_scheduler);

        initilizeMap();
        tv_title_actionbar.setText("Home");


        btn_start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (isMyServiceRunning()) {

                    stopTracking();
                    finish();
                    timer.setBase(SystemClock.elapsedRealtime() + time_stop);
                    timer.stop();
                    mapTrack.setChronometerRunning(false);
                    btn_pause.setVisibility(View.VISIBLE);
                    if (mapTrack.getRun_cycle() == 0) {
                        tv_status.setText("Running");

                    } else if (mapTrack.getRun_cycle() == 1) {
                        tv_status.setText("Cycling");
                    }

                    stopVar = false;
                    tv_status.setText("Stopped");
                    btn_pause.setVisibility(View.GONE);
                    btn_start.setText("Start");
                } else {
                    pp = false;
                    mapTrack.clearEditor();
                    if (googleMap != null) {
                        googleMap.clear();
                    }
                    if (mapTrack.getRun_cycle() == 0) {
                        tv_status.setText("Running");

                    } else if (mapTrack.getRun_cycle() == 1) {
                        tv_status.setText("Cycling");
                    }
                    // clear_editor

                    startTracking();
                    stopVar = true;
                    CommonClass.showToast(HomeScreen.this, "Setting up GPS");
                    btn_start.setText("Stop");
                    // btn_pause.setVisibility(View.VISIBLE);

                }

            }
        });

        btn_pause.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                if (mapTrack.isChronometerRunning() == true) {
                    timer.stop();
                    timeWhenStopped = timer.getBase() - SystemClock.elapsedRealtime();
                    // mapTrack.setStopped_time(timeWhenStopped);
                    mapTrack.setChronometerRunning(false);
                    pauseTracking();
                    btn_pause.setText("Resume");
                } else if (pp == true) {
                    timer.setBase(SystemClock.elapsedRealtime() + timeWhenStopped);
                    timer.start();
                    mapTrack.setChronometerRunning(true);
                    System.out.println("timer is resumed");
                    resumeTracking();
                    btn_pause.setText("Pause");
                }
            }
        });


        if (gps.canGetLocation()) {
            animateCamera(gps.getLatitude(), gps.getLongitude());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            initilizeMap();
            registerReciever();
            // added is my service running
            if (mapTrack != null && mapTrack.getLocationList().size() > 0) {
                if (googleMap != null) {
                    googleMap.clear();
                }
                drawPrimaryLinePath(mapTrack.getLocationList());
                double kmValue = showDistanceTrack(mapTrack.getLocationList());
                tv_distance.setText("" + kmValue + " km");
                double speedValue = calculateSpeed(kmValue);
                tv_speed.setText("" + speedValue + "m/sec");
            }

            if (isMyServiceRunning() && mapTrack.getLocationList() != null) {
                btn_start.setText("Stop");
                btn_pause.setVisibility(View.VISIBLE);
            } else {
                btn_start.setText("Start");
                btn_pause.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
            }
        }

        if (googleMap != null) {
            googleMap.getUiSettings().setZoomControlsEnabled(false);
            googleMap.getUiSettings().setCompassEnabled(false);

        }
    }

    public void animateCameraTo() {
        List<LocationModel> locationlist = mapTrack.getLocationList();
        if (locationlist.size() == 1) {
            LatLng prev = new LatLng(locationlist.get(0).getLat(), locationlist.get(0).getLng());
            googleMap.getUiSettings().setZoomControlsEnabled(true);
            googleMap.getUiSettings().setCompassEnabled(true);
            animateCamera(locationlist.get(0).getLat(), locationlist.get(0).getLng());
            googleMap.addMarker(new MarkerOptions().position(prev).title("Start").snippet("location")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
            timer.setBase(SystemClock.elapsedRealtime() + time_stop);
            timer.start();
            pp = true;
            // added visibility
            btn_pause.setVisibility(View.VISIBLE);
            mapTrack.setChronometerRunning(true);
        } else if (locationlist.size() > 1) {
            drawMap(locationlist);
        }
        double kmValue = showDistanceTrack(locationlist);
        tv_distance.setText("" + kmValue + " km");
        double speedValue = calculateSpeed(kmValue);
        if (kmValue == 0) {
            tv_speed.setText("0 m/sec");
        } else {
            tv_speed.setText("" + speedValue + " m/sec");
        }
    }

    public double showDistanceTrack(List<LocationModel> locationlist) {
        double roundOff = 0;
        if (locationlist != null && locationlist.size() > 1) {
            double mytrack = distance(HomeScreen.this, locationlist);
            double km = mytrack / 1000;
            roundOff = round(km);
        }
        return roundOff;
    }

    public double round(double value) {
        value = Math.floor(value * 100) / 100;
        return value;
    }

    public double calculateSpeed(double distance) {
        double speed = 0;
        double roundOff = 0;
        long timeElapsed = SystemClock.elapsedRealtime() - timer.getBase();
        int hours = (int) (timeElapsed / 3600000);
        int minutes = (int) (timeElapsed - hours * 3600000) / 60000;
        int seconds = (int) (timeElapsed - hours * 3600000 - minutes * 60000) / 1000;

        double m1 = minutes * 60;
        double h1 = hours * 3600;
        double total_seconds = m1 + h1 + seconds;
        speed = (distance * 1000) / total_seconds;
        // double m1 = minutes / 60;
        // double s1 = seconds / 3600;
        // double total_hours = hours + m1 + s1;
        // speed = distance / total_hours;
        // return speed;

        roundOff = round(speed);
        return roundOff;

    }

    public void animateCamera(final double lat, final double lng) {
        CameraPosition camPosition = googleMap.getCameraPosition();
        if (!((Math.floor(camPosition.target.latitude * 100) / 100) == (Math.floor(lat * 100) / 100)
                && (Math.floor(camPosition.target.longitude * 100) / 100) == (Math.floor(lng * 100) / 100))) {
            googleMap.getUiSettings().setScrollGesturesEnabled(false);
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15),
                    new CancelableCallback() {

                        @Override
                        public void onFinish() {
                            googleMap.getUiSettings().setScrollGesturesEnabled(true);

                        }

                        @Override
                        public void onCancel() {
                            googleMap.getUiSettings().setAllGesturesEnabled(true);

                        }
                    });
        }

    }

    public double distance(Context context, List<LocationModel> mMapList) {
        double previousLatitude = 0;
        double previousLongitude = 0;
        float distance[] = new float[2];
        double totalDistance = 0;
        for (int i = 0; i < mMapList.size(); ++i) {
            LatLng latLng = new LatLng(mMapList.get(i).getLat(), mMapList.get(i).getLng());
            if (i == 0) {
                previousLatitude = latLng.latitude;
                previousLongitude = latLng.longitude;
                continue;
            }

            Location.distanceBetween(previousLatitude, previousLongitude, latLng.latitude, latLng.longitude, distance);
            totalDistance = totalDistance + distance[0];
            previousLatitude = latLng.latitude;
            previousLongitude = latLng.longitude;
        }

        return totalDistance;

    }

    public void drawMap(List<LocationModel> list) {
        LatLng prev = new LatLng(list.get(list.size() - 2).getLat(), list.get(list.size() - 2).getLng());
        LatLng my = new LatLng(list.get(list.size() - 1).getLat(), list.get(list.size() - 1).getLng());
        CameraPosition cameralocation = new CameraPosition.Builder()
                .target(new LatLng(list.get(list.size() - 1).getLat(), list.get(list.size() - 1).getLng())).zoom(17)
                .bearing(0).tilt(25).build();
        googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameralocation));
        googleMap.addPolyline(new PolylineOptions().add(prev, my).width(5).color(Color.BLUE));
    }

    private void drawPrimaryLinePath(List<LocationModel> listLocsToDraw) {
        if (googleMap == null) {
            return;
        }

        if (listLocsToDraw.size() < 2) {
            return;
        }
        if (listLocsToDraw.size() > 0) {
            LatLng prev = new LatLng(listLocsToDraw.get(0).getLat(), listLocsToDraw.get(0).getLng());
            googleMap.addMarker(new MarkerOptions().position(prev).title("Start").snippet("location")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
        }
        if (listLocsToDraw != null && listLocsToDraw.size() > 1 && !isMyServiceRunning()) {
            googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(listLocsToDraw.get(listLocsToDraw.size() - 1).getLat(),
                            listLocsToDraw.get(listLocsToDraw.size() - 1).getLng()))
                    .title("Stop").snippet("location")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
        }

        PolylineOptions options = new PolylineOptions();
        options.color(Color.BLUE);
        options.width(5);
        options.visible(true);

        for (LocationModel model : listLocsToDraw) {
            options.add(new LatLng(model.getLat(), model.getLng()));
        }
        googleMap.addPolyline(options);
    }

    public void registerReciever() {
        mReceiver = new LocationReciever();
        IntentFilter filter = new IntentFilter();
        filter.addAction(action);
        registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onPause() {
        unregisterReciever();
        super.onPause();
    }

    public void unregisterReciever() {
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    public void startTracking() {
        System.out.println("I am in start tracking");
        Toast.makeText(getApplicationContext(), "in start tracking", Toast.LENGTH_SHORT).show();
        startService(new Intent(HomeScreen.this, GoogleMapLocationService.class));

    }

    public void pauseTracking() {
        stopService(new Intent(HomeScreen.this, GoogleMapLocationService.class));
        if (mapTrack.getLocationList() != null && mapTrack.getLocationList().size() > 1) {
            googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(mapTrack.getLocationList().get(mapTrack.getLocationList().size() - 1).getLat(),
                            mapTrack.getLocationList().get(mapTrack.getLocationList().size() - 1).getLng()))
                    .title("Stop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
                    .snippet("location"));
            Toast.makeText(getApplicationContext(), "in pause tracking", Toast.LENGTH_SHORT).show();
        }
    }

    public void resumeTracking() {
        System.out.println("I am in resume tracking");
        Toast.makeText(getApplicationContext(), "in resume tracking", Toast.LENGTH_SHORT).show();
        startService(new Intent(HomeScreen.this, GoogleMapLocationService.class));
    }

    public void stopTracking() {
        stopService(new Intent(this, GoogleMapLocationService.class));
        if (mapTrack.getLocationList() != null && mapTrack.getLocationList().size() > 1) {
            googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(mapTrack.getLocationList().get(mapTrack.getLocationList().size() - 1).getLat(),
                            mapTrack.getLocationList().get(mapTrack.getLocationList().size() - 1).getLng()))
                    .title("Stop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                    .snippet("location"));
            Toast.makeText(getApplicationContext(), "in stop tracking", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        if (stopVar == false) {
            if (doubleBackToExitPressedOnce) {
                super.onBackPressed();
                return;
            }

            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        }

    }

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (GoogleMapLocationService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

这是我的服务类:

import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.widget.Toast;

public class GoogleMapLocationService extends Service {
    String action = "com.example.googlemapreciever.location";
    MapSharedPref prefrences;

    @Override
    public void onCreate() {
        super.onCreate();
        prefrences = new MapSharedPref(getApplicationContext());
        Toast.makeText(getApplicationContext(), "create", Toast.LENGTH_SHORT)
                .show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new LocationTracker(getApplicationContext(), new TrackerSettings()
                .setUseGPS(true).setUseNetwork(false).setUsePassive(false)
                .setTimeBetweenUpdates(1500).setMetersBetweenUpdates(20)) {

            @Override
            public void onLocationFound(Location location) {
                if (location != null && location.getLatitude() != 0
                        && location.getLongitude() != 0) {
                    LocationModel model = new LocationModel();
                    model.setLat(location.getLatitude());
                    model.setLng(location.getLongitude());
                    prefrences.setLocationList(model);
                    broadcastLocation();
                }
            }

            @Override
            public void onTimeout() {
            }
        };

        Toast.makeText(getApplicationContext(), "onstartcommand",
                Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    public float getDistance(double lat1, double lng1, double lat2, double lng2) {
        float[] distance = new float[2];
        Location.distanceBetween(lat1, lng1, lat2, lng2, distance);
        return distance[0];

    }

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

    public void broadcastLocation() {
        Intent intent = new Intent();
        intent.setAction(action);
        Toast.makeText(getApplicationContext(), "Inside broadcast location",
                Toast.LENGTH_SHORT).show();
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        System.out.println("I am in stop service");
        Toast.makeText(getApplicationContext(), "destroy", Toast.LENGTH_SHORT)
                .show();

        super.onDestroy();
    }
}

0 个答案:

没有答案