簡體   English   中英

Android 活動不會停止服務和位置更新

[英]Android Activity doesn't stop service and location updates

我正在使用谷歌 api 客戶端跟蹤 MainActivity 中用戶的當前位置並更新當前位置的標記。 在服務中,我跟蹤用戶的當前位置並將其存儲到 firebase 實時數據庫中。

MainActivity中,我使用按鈕停止服務,方法是斷開 api 客戶端以及停止服務。

根據類似的問題,我已經在我的服務中實現了 ondestroy。 在 api 客戶端斷開連接后,服務仍在運行並將位置存儲到 firebase。

如何停止此服務?

地圖活動:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    process = (Button)findViewById(R.id.buttonMaps);
    stoptrek = (Button) findViewById(R.id.buttonService);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    process.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MapsActivity.this,"processing...",Toast.LENGTH_SHORT).show();
            Intent i = new Intent(MapsActivity.this,MapsActivity2.class);
            MapsActivity.this.startActivity(i);
            finishActivity(1);

        }
    });

    stoptrek.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stopTrackerService();
            stopService(new Intent(MapsActivity.this, TrackingService.class));
            Toast.makeText(MapsActivity.this, "GPS tracking disabled", Toast.LENGTH_SHORT).show();
        }
    });
}

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
            startTrackerService();
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
        startTrackerService();
    }
}


public void stopTrackerService()
{
    if(mGoogleApiClient.isConnected()){
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) MapsActivity.this);
        mGoogleApiClient.disconnect();
        Toast.makeText(MapsActivity.this,"Disconnected api client",Toast.LENGTH_SHORT).show();
    }
    else
        Toast.makeText(MapsActivity.this,"api client is already disconnected",Toast.LENGTH_SHORT).show();
}

服務:

公共 class TrackingService 擴展服務 {

FusedLocationProviderClient client;

private static final String TAG = TrackingService.class.getSimpleName();

public TrackingService() {
}

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

@Override
public void onCreate() {
    super.onCreate();
    buildNotification();
    loginToFirebase();
}
@Override
public void onDestroy()
{
    stopSelf();
}

//Create the persistent notification//

private void buildNotification() {
    String stop = "stop";
    // Create the persistent notification
    Notification.Builder builder = new Notification.Builder(this)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.tracking_enabled_notif))
            .setOngoing(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        startForeground(1, builder.build());
    }
}

private void loginToFirebase() {

    String email = "xyz@sdl.com";//getString(R.string.test_email);
    String password = "xyz123";//getString(R.string.test_password);


    FirebaseAuth.getInstance().signInWithEmailAndPassword(
            email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(Task<AuthResult> task) {


            if (task.isSuccessful()) {

                requestLocationUpdates();
            } else {
                Log.d(TAG, "Firebase authentication failed");
            }
        }
    });
}

private void requestLocationUpdates() {
    LocationRequest request = new LocationRequest();
    request.setInterval(5000);

    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    client = LocationServices.getFusedLocationProviderClient(this);
    final String path = "location";
    int permission = ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);

    if (permission == PackageManager.PERMISSION_GRANTED) {

        client.requestLocationUpdates(request, new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                String uid = user.getUid();

                DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
                Location location = locationResult.getLastLocation();
                if (location != null) {
                    Toast.makeText(TrackingService.this,"recently add to DB",Toast.LENGTH_SHORT).show();
                    ref.child(uid).child(path).push().setValue(location);
                }
            }
        }, null);
    }
}

我有與 googleapiclient 斷開連接的地圖活動,但即使在停止位置更新和服務之后,位置也會被推送到數據庫中。

請告訴我如何完全停止服務。 謝謝

此方法檢查服務是否正在運行。 如果服務正在運行,那么它將返回 true,否則返回 false。

檢查運行服務:

public static boolean isServiceRunning(Context context, Class<?> cls) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (activityManager != null) {
        for (ActivityManager.RunningServiceInfo runningServiceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
            if (cls.getName().equals(runningServiceInfo.service.getClassName())) {
                return true;
            }
        }
    }
    return false;
}

停止運行服務:

ActivityStackManager.getInstance().stopLocationService(TrackingService.this);

這個怎么運作:

if (isServiceRunning(this, TrackingService.class)) {
    ActivityStackManager.getInstance().stopLocationService(TrackingService.this);
}

注意:在您想要斷開位置更新的地方也停止服務,我可以看到您正在通過 stopTrackerService() 方法斷開位置更新

例如:

  public void stopTrackerService()
    {

    if (isServiceRunning(this, TrackingService.class)) {
        ActivityStackManager.getInstance().stopLocationService(TrackingService.this);
    }

    if(mGoogleApiClient.isConnected()){
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) MapsActivity.this);
            mGoogleApiClient.disconnect();
            Toast.makeText(MapsActivity.this,"Disconnected api client",Toast.LENGTH_SHORT).show();
    }
     else
            Toast.makeText(MapsActivity.this,"api client is already disconnected",Toast.LENGTH_SHORT).show();
    }

活動堆棧管理器

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

public class ActivityStackManager {

    private static final ActivityStackManager mActivityStack = new ActivityStackManager();

    private ActivityStackManager() {
    }

    public static ActivityStackManager getInstance() {
        return mActivityStack;
    }

    public void stopLocationService(Context context) {
        if (isServiceRunning(context, TrackingService.class)) {
            context.stopService(new Intent(context, LocationService.class));
            Log.e("StackManager", "TrackingServiceStop");
        }
    }

    public void startLocationService(Context context){
        Intent serviceIntent = new Intent(context, TrackingService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM