2017-11-03 4 views
3

전체 활동이 백그라운드에서 작동 할 때뿐만 아니라 전체 서비스가 삭제 될 때 작동해야하는 서비스를 만들고 있습니다.몇 분 후에 서비스가 자동으로 중지됩니다.

1 분 간격으로 서비스에서 위치 좌표를 호출합니다.

그러나 서비스를 시도하면 12-15 분 후에 서비스가 자동으로 종료됩니다.

사용자 상호 작용시 활동이 완료 될 때까지 그리고 서비스가 종료 될 때까지 서비스가 끝없이 작동되기를 바랍니다. SensorRest을 여기

public class SensorService extends Service { 
 
    public int counter=0; 
 
    public static final int NINTY_SECONDS = 90000; 
 
    public static Boolean isRunning = false; 
 
    public LocationManager mLocationManager; 
 
    public Get_Coordinates mLocationListener; 
 
    public GetSharedPreference sharedPreference; 
 
    @Override 
 
    public void onCreate() { 
 
     mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
 
     mLocationListener = new Get_Coordinates(getApplicationContext()); 
 
     sharedPreference = new GetSharedPreference(getApplicationContext()); 
 
     startTimer(); 
 
     super.onCreate(); 
 
    } 
 
    public SensorService(Context applicationContext) { 
 
     super(); 
 
     Log.i("HERE", "here I am!"); 
 
    } 
 

 
    public SensorService() { 
 
    } 
 
    @Override 
 
    public int onStartCommand(Intent intent, int flags, int startId) { 
 
     super.onStartCommand(intent, flags, startId); 
 
     return START_STICKY; 
 
    } 
 
    @Override 
 
    public void onDestroy() { 
 
     super.onDestroy(); 
 
     Log.i("EXIT", "ondestroy!"); 
 
     Intent broadcastIntent = new Intent("com.android.startBgService"); 
 
     broadcastIntent.putExtra("abc","abcd"); 
 
     sendBroadcast(broadcastIntent); 
 
     stoptimertask(); 
 
    } 
 

 
    private Timer timer; 
 
    private TimerTask timerTask; 
 
    long oldTime=0; 
 
    public void startTimer() { 
 
     //set a new Timer 
 
     timer = new Timer(); 
 

 
     //initialize the TimerTask's job 
 
     initializeTimerTask(); 
 

 
     //schedule the timer, to wake up every 1 second 
 
     timer.schedule(timerTask, NINTY_SECONDS, NINTY_SECONDS); // 
 
    } 
 

 
    /** 
 
    * it sets the timer to print the counter every x seconds 
 
    */ 
 
    public void initializeTimerTask() { 
 
     timerTask = new TimerTask() { 
 
      public void run() { 
 
       // Log.i("in Etro Sendor", "in timer ++++ "+ (counter++)); 
 
       if (Check_Internet_Con.isConnectingToInternet(getApplicationContext())) { 
 

 
        if (!isRunning) { 
 
         startListening(); 
 
        } 
 
        try { 
 
         if (sharedPreference.getActiveUserId() > 0) { 
 
          mLocationListener.getLocation(); 
 
          mLocationListener.insertCoordinatesInSqlite(); 
 
         } 
 
        } catch (IOException e) { 
 
         e.printStackTrace(); 
 
        } 
 
       } 
 
      } 
 
     }; 
 
    } 
 

 
    /** 
 
    * not needed 
 
    */ 
 
    public void stoptimertask() { 
 
     //stop the timer, if it's not already null 
 
     if (timer != null) { 
 
      timer.cancel(); 
 
      timer = null; 
 
     } 
 
    } 
 

 
    @Nullable 
 
    @Override 
 
    public IBinder onBind(Intent intent) { 
 
     return null; 
 
    } 
 
    public void startListening() { 
 
     if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
 
       || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 
 
      if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) 
 
       mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener, Looper.getMainLooper()); 
 

 
      if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) 
 
       mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener,Looper.getMainLooper()); 
 
     } 
 
     isRunning = true; 
 
    } 
 
}

내 매니페스트

<service 
 
      android:name="com.lunetta.etro.e_tro.SensorService" 
 
      android:enabled="true"></service> 
 
     <service 
 
      android:name="com.lunetta.etro.e_tro.SecondService" 
 
      android:enabled="true" > 
 
     </service> 
 

 
     <receiver 
 
      android:name=".SensorRestarterBroadcastReceiver" 
 
      android:enabled="true" 
 
      android:exported="true" 
 
      android:label="RestartServiceWhenStopped"> 
 
      <intent-filter> 
 
       <action android:name="com.android.startBgService" /> 
 
       <action android:name="android.intent.action.BOOT_COMPLETED" /> 
 
      </intent-filter> 
 
     </receiver>

입니다 그리고 다음은 다음과 같이

내 서비스 클래스이다 arterBroadcastReceiver 클래스는

public class SensorRestarterBroadcastReceiver extends BroadcastReceiver { 
 
    @Override 
 
    public void onReceive(Context context, Intent intent) { 
 
     Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!"); 
 
     context.startService(new Intent(context, SensorService.class)); 
 
     
 
    } 
 
}

+0

이것은 Android O 배경 실행 제한 때문에 발생할 수 있습니다. https://developer.android.com/about/versions/oreo/background.html –

+0

onStartCommand에서 START_REDELIVER_INTENT을 (를) 사용하여 반환 해 보았습니까? – Dilip

+0

포 그라운드 서비스 사용 https://stackoverflow.com/questions/6397754/android-implementing-startforeground-for-a-service – rajahsekar

답변

1

예는 구글에 의해 넣어 새로운 문서를 확인, 작동이 중지됩니다, 그것은 위치 배터리 성능을 위해 어떻게 작동하는지 완전히 변경, 그리고 예는 성능에 큰 거래 효과가 나는 변경 내 매우 구체적인 작업을 위해 완전히. 또한 그들은 구글

https://developer.android.com/training/building-location.html

하여 새로운 업데이트 된 문서가 난 당신 같은 요구 사항을 구현하는 가장 좋은 방법 잘못된

확인있는 일이라고 주장 않는 다른 REPOS 사용을 중지하고 약 60K 장치에 걸쳐 살고있다 23 이상의 버전을 가진 JobService를 사용하는 Android API의 버전에 따라 백그라운드 서비스와 함께 완벽하게 작동합니다. 그에 따라 LocationProvider API 및 위치 공급자 클라이언트 API를 사용하십시오.

개인적인 경험과 함께 나는 이것을 말할 것이다. 코드의 옛 스타일은 몇 시간 만에 장치 배터리를 방전시키는 데 사용된다. 이제는 내 코드가 거의 쓰이지 않고 거의 15 %의 전체 사용량을 소비한다. 그게 큰 소비 변화 야.

+0

그럼 어떻게 안내 할 수 있습니까? 함께하면 도움이 될 것입니다. –

+0

나는 똑똑하고 전문적으로 동일한 코드를 구현해야한다고 말했기 때문에 JobService 양식 23 이상을 사용해야합니다. 이전에는 사용하고 수출해야하는 서비스 –

+0

감사합니다. 힘든 일을 많이했습니다. –

2

https://developer.android.com/guide/components/bound-services.html

"또 다른 응용 프로그램 구성 요소를 제공하며 무기한 백그라운드에서 실행되지 않습니다 동안 바운드 서비스는 일반적으로 만 살고있다."

무기한으로 실행하려면 무한대로 존재하는 UI 구성 요소에 서비스를 바인딩해야합니다. Android 알림을 사용할 수 있습니다. 이것은 전경 서비스입니다.

https://developer.android.com/guide/components/services.html#Foreground

관련 문제