2016-05-17 126 views
-1

我在我的android應用程序中使用Service,即使在我的應用程序未運行時也通過Fused Location Provider持續獲取位置更新。但問題是Service正在運行,只要我的應用程序正在運行,當我關閉我的應用程序Service也會在某個時間後停止。那麼請幫忙?服務在關閉應用程序時自動停止

啓動服務

Intent startServiceIntent = new Intent(getApplicationContext(), LocationDetector.class); 
startService(startServiceIntent); 

服務代碼:

package com.example.jahanzebahmed.smartlocator; 

import android.app.Service; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.os.Build; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.support.v4.content.ContextCompat; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 



public class LocationDetector extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

    Location mLastLocation; 
    private GoogleApiClient mGoogleApiClient; 
    private LocationRequest mLocationRequest; 
    static String lat=null, lon=null; 
    static boolean enableNotifications = false; 
    static boolean enableEmails = false; 


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


    @Override 
    public void onCreate() { 
     super.onCreate(); 
     enableNotifications = true; 
     if(!MainActivity.notifications_switch.isChecked()) 
      MainActivity.notifications_switch.setChecked(true); 
     buildGoogleApiClient(); 
    } 


    synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     mGoogleApiClient.connect(); 
     return Service.START_NOT_STICKY; 
    } 


    @Override 
    public void onConnected(Bundle bundle) { 
     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     mLocationRequest.setInterval(5000); // Update location every se 
     mLocationRequest.setFastestInterval(5000); 
     mLocationRequest.setSmallestDisplacement(0); 
     if ((Build.VERSION.SDK_INT >= 23) && (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { 
      return; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     if (mLastLocation != null) { 
      lat = String.valueOf(mLastLocation.getLatitude()); 
      lon = String.valueOf(mLastLocation.getLongitude()); 
     } 
     checkForNotification(); 
    } 


    @Override 
    public void onLocationChanged(Location location) { 
     lat = String.valueOf(location.getLatitude()); 
     lon = String.valueOf(location.getLongitude()); 
     checkForNotification(); 
    } 


    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     mGoogleApiClient.disconnect(); 
     enableEmails = false; 
     enableNotifications = false; 
     stopSelf(); 
    } 


    void checkForNotification() { 
     Location location = new Location("fused"); 
     location.setLatitude(new Double(lat)); 
     location.setLongitude(new Double(lon)); 
     if(enableNotifications) 
      new CheckReminders(getApplicationContext()).execute(location); 
     if(enableEmails) 
      new EmailsHandler(getApplicationContext()).execute(location); 
    } 


    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     buildGoogleApiClient(); 
    } 


    @Override 
    public void onConnectionSuspended(int i) { 

    } 

} 
+0

首先,該服務可能會被任務管理器(外部應用程序或系統應用程序)殺死。在這種情況下,您必須在此任務管理器中手動保護此應用程序。沒有辦法通過編程來完成,所以你必須通知你的用戶。爲了讓您的服務保持活躍狀態​​,您可以返回START_STICKY,如果資源空閒(或儘快),可以重新創建服務。您也可以開始您的服務作爲前臺服務(由於電池消耗,只在特殊情況下才推薦)。 – Opiatefuchs

+0

@Opiatefuchs我應該使用'AlarmManager'而不是'Service'嗎? –

+0

@ SajalAli,返回Service.START_NOT_STICKY;此行將在應用程序關閉時關閉服務。 – TheGreat004

回答

0

檢查:

public class LocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener { 

private static final String TAG = "SERVICE CLASS"; 
private GoogleApiClient mGoogleApiClient; 
// A request to connect to Location Services 
private LocationRequest mLocationRequest; 

private LocationListener locationListener; 
//public MapsActivity mapsActivity; 

public static String latitude; 
public static String longitute; 
public static String s; 

private static final int REQUEST_CODE_LOCATION = 2; 

private static double kph = 3.6; 
private double speed = 0.0; 

/*public LocationUpdate(MapsActivity mapsActivity) { 
    this.mapsActivity=mapsActivity; 
}*/ 

private class LocationListener implements com.google.android.gms.location.LocationListener { 

    @Override 
    public void onLocationChanged(Location location) { 

     latitude = String.valueOf(location.getLatitude()); 
     longitute = String.valueOf(location.getLongitude()); 
     Log.d("location lat",location.getLatitude()+""); 
     Log.d("location long",location.getLongitude()+""); 
    } 
} 

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

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // Log.e(TAG, "onStartCommand"); 
    super.onStartCommand(intent, flags, startId); 
    boolean stopService = false; 
    if (intent != null) 
     stopService = intent.getBooleanExtra("stopservice", false); 

    System.out.println("stopservice " + stopService); 

    locationListener = new LocationListener(); 
    if (stopService) 
     stopLocationUpdates(); 
    else { 
     if (!mGoogleApiClient.isConnected()) 
      mGoogleApiClient.connect(); 
    } 
    return START_STICKY; 
} 

@Override 
public void onCreate() { 
    // Log.e(TAG, "onCreate"); 
    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API).addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this).build(); 
} 

@Override 
public void onDestroy() { 
    // Log.e(TAG, "onDestroy"); 
    super.onDestroy(); 
} 

public void stopLocationUpdates() { 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener); 
    if (mGoogleApiClient.isConnected()) 
     mGoogleApiClient.disconnect(); 
} 


@Override 
public void onConnectionFailed(ConnectionResult arg0) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onConnected(Bundle arg0) { 
    // TODO Auto-generated method stub 
    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest.setSmallestDisplacement(10); 
    mLocationRequest.setInterval(3000); 
    mLocationRequest.setFastestInterval(3000); 
    startLocationUpates(); 
} 

private Location startLocationUpates() { 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= 
      PackageManager.PERMISSION_GRANTED) { 

    } else { 
     // Locatiossssssssn permission has been granted, continue as usual. 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener); 
     // Log.i("update location","Start update location"+myLocation.getLongitude()); 
    } 
    s = String.valueOf(LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)); 

    return LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
} 

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

這仍然將更新位置時,應用程序關閉。

相關問題