2017-05-01 24 views
0

wakelock 기능과 함께 서비스 클래스를 사용하여 화면이 꺼져 있거나 잠자기 상태에서도 응용 프로그램이 백그라운드에서 작동합니다. 하지만 강제로 응용 프로그램을 닫을지라도 wakelock이 해제되지 않고 앱이 백그라운드에서 작동하고 있습니다. 아래에 서비스 클래스 코드를 첨부했습니다.앱이 강제 종료 된 후에도 Wakelock이 해제되지 않습니다.

니핏

 @Override 
public void onCreate() { 
    Log.e(TAG, "onCreate"); 
    initializeLocationManager(); 
    PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 
    wakeLock= mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); 
    wakeLock.acquire(); 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[1]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "network provider does not exist, " + ex.getMessage()); 
    } 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[0]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "gps provider does not exist " + ex.getMessage()); 
    } 
} 

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

    wakeLock.release(); 
} 

I는 서비스 클래스의 메소드에서 onCreate에서 가동 잠금을 획득하고 동일한 클래스들의 OnDestroy 방법을 공개하고있다. 이 문제를 극복하는 방법. 나는 새로운 서비스와 wakelocks입니다. 미리 감사드립니다.

편집 1 :

MainActivity 코드 :

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


    Intent serviceIntent = new Intent(context , MyLocationService.class); 
    context.startService(serviceIntent ); 



    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 
    if (!isGooglePlayServicesAvailable()) { 
     finish(); 
    } else { 
     Log.d("onCreate", "Google Play Services available."); 
    } 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

위치 서비스

public class MyLocationService extends IntentService { 
private static final String TAG = "MyLocationService"; 
private LocationManager mLocationManager = null; 
private static final int LOCATION_INTERVAL = 3000; 
private static final float LOCATION_DISTANCE = 0f; 
Context context = this; 
PowerManager.WakeLock wakeLock; 
public int e=0; 

LocationListener[] mLocationListeners = new LocationListener[]{ 
     new LocationListener(LocationManager.GPS_PROVIDER), 
     new LocationListener(LocationManager.NETWORK_PROVIDER) 
}; 

/** 
* Creates an IntentService. Invoked by your subclass's constructor. 
* 
* @param name Used to name the worker thread, important only for debugging. 
*/ 
public MyLocationService(String name) { 
    super(name); 
} 

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

@Override 
protected void onHandleIntent(Intent intent) { 
    wakeLock.release(); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.e(TAG, "onStartCommand"); 
    super.onStartCommand(intent, flags, startId); 
    Toast.makeText(this, "MyService Started.", Toast.LENGTH_SHORT).show(); 
    return START_STICKY; 
} 

@Override 
public void onCreate() { 
    Log.e(TAG, "onCreate"); 
    initializeLocationManager(); 
    PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 
    wakeLock= mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); 
    wakeLock.acquire(); 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[1]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "network provider does not exist, " + ex.getMessage()); 
    } 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[0]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "gps provider does not exist " + ex.getMessage()); 
    } 
} 

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


    if (mLocationManager != null) { 
     for (int i = 0; i < mLocationListeners.length; i++) { 
      try { 
       if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        // TODO: Consider calling 
        // ActivityCompat#requestPermissions 
        // here to request the missing permissions, and then overriding 
        // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
        //           int[] grantResults) 
        // to handle the case where the user grants the permission. See the documentation 
        // for ActivityCompat#requestPermissions for more details. 
        return; 
       } 
       mLocationManager.removeUpdates(mLocationListeners[i]); 
      } catch (Exception ex) { 
       Log.i(TAG, "fail to remove location listners, ignore", ex); 
      } 
     } 
    } 
} 

private void initializeLocationManager() { 
    Log.e(TAG, "initializeLocationManager"); 
    if (mLocationManager == null) { 
     mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
    } 
} 

// create LocationListener class to get location updates 
private class LocationListener implements android.location.LocationListener 
{ 
    Location mLastLocation; 
    double latitude; 
    double longitude; 
    LatLng latLngcurrent; 


    public LocationListener(String provider) 
    { 
     Log.e(TAG, "LocationListener " + provider); 
     mLastLocation = new Location(provider); 
    } 

    @Override 
    public void onLocationChanged(Location location) 
    { 
     Log.e(TAG, "onLocationChanged: " + location); 
     mLastLocation.set(location); 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
     Store.latu=latitude; 
     Store.longu=longitude; 
     latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude()); 
     Toast.makeText(context,"Location " + String.valueOf(e), Toast.LENGTH_SHORT).show(); 
     e++; 
     Toast.makeText(MyLocationService.this,Store.latu+" "+Store.longu, Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onProviderDisabled(String provider) 
    { 
     Log.e(TAG, "onProviderDisabled: " + provider); 
    } 

    @Override 
    public void onProviderEnabled(String provider) 
    { 
     Log.e(TAG, "onProviderEnabled: " + provider); 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) 
    { 
     Log.e(TAG, "onStatusChanged: " + provider); 
    } 
} 
} 
+0

이동 wakeLock.release(); before super.onDestroy(); –

+0

늦게 답변 해 주셔서 감사합니다. 나는 onDestroy() 전에 시도했다. 그러나 여전히 변화가 없습니다. 백그라운드에서 응용 프로그램을 닫았지만 여전히 값을 업데이트하고 있습니다. @DivyeshPatel –

+0

의도 서비스를 사용하고 있습니까? –

답변

0

솔루션 : 나는 마침내 이것에 대한 해결책을 발견했다 . 매우 간단합니다. 태그를 사용하는 동안 매니페스트에서이 줄도 추가하십시오.

발췌문 :

<service android:name=".MyLocationService" 
android:stopWithTask="true"></service> 

우리는 응용 프로그램을 닫습니다 강제 때 stopWithTask 서비스를 중지하고, 가동 잠금도 중지됩니다.

here은 설명서입니다. 이 응용 프로그램을 추가 한 후 잘 작동합니다.