2017-01-17 1 views
0

내 앱이 제거 될 때까지 서비스를 계속 실행해야합니다.이 서비스에서 위도를 보내야합니다. 그것이 내가했던 곳 실수를특정 시간 간격으로 서버에 lat 값을 지속적으로 보내야하지만 서비스가 백그라운드에서 제대로 실행되지 않습니다.

내 활동을 못하고 있어요 파괴하고 그 후 긴 값이 지속적으로 모든 일 분

에 대한 문제는 내 서비스는 며칠 동안 제대로 실행되고 .........

알람 관리자를 사용하여 내 서비스에 전화 중입니다.

617,451,515,....... 내 BootReciver

public void onReceive(Context context, Intent intent) { 
     ... 
    context.startService(new Intent(context,LongService.class)); 
..} 

내 LongService ................

@Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
     Log.d("first launch", "first oncreate launch"); 
     dbHandler = new DbHandler(LongService.this); 
     buildGoogleApiClient(); 
     createLocationRequest(); 
    } 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 


    @Override 
    public void onDestroy() { 
     // TODO Auto-generated method stub 
     Toast.makeText(getBaseContext(), "KiteEye Tracking is Destroyed Please Open it Again ", Toast.LENGTH_SHORT).show(); 
     super.onDestroy(); 
    } 

    @Override 
    public void onTaskRemoved(Intent rootIntent) { 
     super.onTaskRemoved(rootIntent); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     // TODO Auto-generated method stub 
     super.onStart(intent, startId); 


     SharedPreferences bb = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
     Saved_Vehicle_ID = bb.getString("VehicleId", ""); 
     VehicleName = bb.getString("VehicleName", ""); 
     handler.postDelayed(new Runnable() { 
      public void run() { 
       Count = Count + 1; 
       insertDB(str1, str2, date); 
       if (isConnectingToInternet(LongService.this)) { 
        SendOfflineLatLongToServer(); 
       } 
       Log.e(TAG, "count" + Count); 
       Log.e(TAG, "(running.!!!!!!!)" + Saved_Vehicle_ID + Saved_interval); 
       Log.e(TAG, "(Cuurent location.!!!!!!!)" + Current_Address + Saved_interval); 

       if (Count >=60) { 
        Log.e(TAG, "count reached to Maximum "); 
        if(Current_Address!=null) { 
         if (date1 != null) { 
          sendMessageToActivity(getApplicationContext(), Current_Address, date1); 
          KeyguardManager km = (KeyguardManager) getApplicationContext() 
            .getSystemService(Context.KEYGUARD_SERVICE); 
          final KeyguardManager.KeyguardLock kl = km 
            .newKeyguardLock("MyKeyguardLock"); 
          kl.disableKeyguard(); 
          PowerManager pm = (PowerManager) getApplicationContext() 
            .getSystemService(Context.POWER_SERVICE); 
          PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK 
            | PowerManager.ACQUIRE_CAUSES_WAKEUP 
            | PowerManager.ON_AFTER_RELEASE, "MyWakeLock"); 
          wakeLock.acquire(); 
          Count = 0; 
         } 
        } 
       } 
       sendMessageToActivity(getApplicationContext(), Current_Address, date1); 
       handler.postDelayed(this, 60000); 
      } 
     }, 60000); 
    } 

    private static void sendMessageToActivity(Context context, String loc, String time) { 
     Intent intent = new Intent("CurrentLocation"); 
     Bundle b = new Bundle(); 
     b.putString("Location", loc); 
     b.putString("Time", time); 
     intent.putExtra("Location", b); 
     intent.putExtra("Time", b); 
     LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 
    } 

    private void insertDB(String str1, String str2, String date) { 
     ... 
    } 

    String S_id, S_lat, S_lon, S_time; 

    private void SendOfflineLatLongToServer() { 
     ... 
    } 

    public void SendLatLongToServer(final String _mid, final String lat, final String lon, final String time) { 
     ... 

    } 

    public static boolean isConnectingToInternet(Context _context) { 
     ..... 
    } 

    public synchronized void buildGoogleApiClient() { 
     ... 
    } 

    /** 
    * Creating location request object 
    */ 
    public void createLocationRequest() { 
     .. 
    } 

    protected void startLocationUpdates() { 

     .. 
    } 

    /** 
    * Stopping location updates 
    */ 
    protected void stopLocationUpdates() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(
       mGoogleApiClient, this); 
    } 

    /** 
    * Google api callback methods 
    */ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " 
       + result.getErrorCode()); 
    } 

    @Override 
    public void onConnected(Bundle arg0) { 

     .. 
    } 

    @Override 
    public void onConnectionSuspended(int arg0) { 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     // Assign the new location 
     mLastLocation = location; 
     // Displaying the new location on UI 
     displayLocation(); 


    } 

    private void displayLocation() { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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; 
     } 
     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 
     if (mLastLocation != null) { 
      double latitude = mLastLocation.getLatitude(); 
      double longitude = mLastLocation.getLongitude(); 
      Geocoder geocoder; 
      List<Address> addresses; 
      geocoder = new Geocoder(this, Locale.getDefault()); 
      try { 
       addresses = geocoder.getFromLocation(latitude, longitude, 7); 
       if (addresses != null) { 
        String address = addresses.get(0).getAddressLine(0); 
        String address1 = addresses.get(0).getSubLocality(); 
        String address2 = addresses.get(0).getLocality(); 
        StringBuilder stringBuilder = new StringBuilder(); 
        stringBuilder.append(address); 
        stringBuilder.append(","); 
        stringBuilder.append(address1); 
        stringBuilder.append(","); 
        stringBuilder.append(address2); 
        Current_Address = stringBuilder.toString(); 

       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      str1 = String.valueOf(latitude); 
      str2 = String.valueOf(longitude); 

      DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
      Date CuurentTime = new Date(mLastLocation.getTime()); 
      date = format.format(CuurentTime); 

      DateFormat format1 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 
      Date CuurentTime1 = new Date(mLastLocation.getTime()); 
      date1 = format1.format(CuurentTime1); 
      Log.d(TAG, "location" + str1 + "\t" + str2); 
      Log.d(TAG, "location" + "date and time" + date); 

      app_preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
      editor = app_preferences.edit(); 
      editor.putString("date", date); 
      editor.putString("CurrentAddress", Current_Address); 
      editor.commit(); 


      MyApplication.getInstance().getPrefManager().setTime(date); 
      MyApplication.getInstance().getPrefManager().setCurrentLocation(Current_Address); 
//   if (Count==0) { 
//    sendMessageToActivity(getApplicationContext(), Current_Address, date); 
//   } 
     } else { 
      Log.e(TAG, "(Couldn't get the location. Make sure location is enabled on the device)"); 
     } 
    } 
    private void displayLocation1() { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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; 
     } 
     mLastLocation = LocationServices.FusedLocationApi 
       .getLastLocation(mGoogleApiClient); 
     if (mLastLocation != null) { 
      double latitude = mLastLocation.getLatitude(); 
      double longitude = mLastLocation.getLongitude(); 
      str1 = String.valueOf(latitude); 
      str2 = String.valueOf(longitude); 
      DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
      Date CuurentTime = new Date(mLastLocation.getTime()); 
      date = format.format(CuurentTime); 
      Log.d(TAG, "loc" + str1 + "\t" + str2); 
      Log.d(TAG, "loc" + "date & time" + date); 
      insertDB(str1, str2, date); 

     } else { 
      Log.e(TAG, "(Couldn't get the location. Make sure location is enabled on the device)"); 
     } 
    } 
    public void removeDB(String id) { 
    ... 
} 
+0

삼성 기기에서 테스트 하시겠습니까? –

+0

며칠 동안 작동하는지 확인한 다음 중지 되었습니까? @ 디부 야 –

+0

그래 며칠 동안 그 서비스가 나중에 파괴되고 있다고 확신합니다. – Divya

답변

0

@PratikDasa가 지적 Android는 시스템 리소스를 회수하기 위해 장시간 실행되는 백그라운드 서비스를 수시로 정리할 수 있습니다. 따라서 백그라운드에서 계속 서비스를 실행해야하는 경우 onStartCommand 메서드를 구현하십시오. 현재 onStart 방법에서 전체 코드를 잘라내어 onStartCommand (OnStart은 오래 전에 사용되지 않음)으로 넣습니다. onStartCommand은 값을 반환해야하며 트릭이있는 곳입니다. 그것에서 START_STICKY를 돌려 보내십시오. 당신이 onStartCommand에서 START_STICKY을 반환 할 때 당신은 당신은 기본적으로 명시 적으로 중지 될 때마다 후 서비스를 다시 시작 안드로이드 시스템을 물어

Android Service API에서이 상수에 대한 자세한 내용을보실 수 있습니다. 위의 링크에서 읽을 수있는 몇 가지주의 사항이 있습니다. 모든 경고 중에서 가장 중요한 점은 시스템이 명시 적으로 서비스를 다시 시작하면 전달 의도가 NULL (서비스를 시작하려고하는 일부 의도가없는 경우) 일 수 있으므로 코드에서 적절하게 처리해야한다는 것입니다.

이러한 사항을 변경하고 기본 테스트를 수행하십시오. 나는 일이 잘 작동해야한다.

+0

tq fr ur [email protected]는이 지식으로 내 지식을 해결하려고 노력할 것입니다. – Divya

+0

괜찮은 @ 디부 야 언제든지 주저없이 문의 할 수 있습니다. 원할 경우 이메일 ID로 저에게 연락 할 수 있습니다. –

+0

위의 해결 방법이 효과가있는 경우 동료 SO 메이트에 대한 향후 참조 용으로 대답으로 태그를 지정하십시오 – Dibzmania

관련 문제