2017-02-14 98 views
-1

當屏幕被鎖定和關閉時,則服務停止向數據庫Mysql發送數據。 ?如何修復2天我無法找到答案, 添加許可激活鎖定 向我解釋爲什麼發生這種情況 那是我的代碼:服務不發送數據

public class GpsService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener { 
    int NOTIFICATION_ID = 123123; 
    private static final String LOGSERVICE = "#######"; 
    private LocationRequest mLocationRequest; 
    private GoogleApiClient mGoogleApiClient; 
    String urlAddress="*****"; 
    String adress ="https://www.google.az/"; 
    String number = "Example2"; 
    String id="2"; 
    String status; 
    String mlatitude, mlogtud; 
    String times; 
    TimerTask task; 
    Timer timer; 
    Date now; 



     public GpsService() { 
    } 


    @Override 
    public void onCreate() { 
     PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); 
     PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
       "MyWakelockTag"); 

     super.onCreate(); 
     wakeLock.acquire(); 
     Notification.Builder builder = new Notification.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher); 
     Notification notification; 
     buildGoogleApiClient(); 
     notification = builder.build(); 
     startForeground(NOTIFICATION_ID, notification); 

     Log.d(LOGSERVICE,"servis leavle"); 
     task=new TimerTask() { 
      @Override 
      public void run() { 

       //SimpleDateFormat example - Date with timezone information 
       Date today = new Date(); 
       SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm"); 
       String date = DATE_FORMAT.format(today); 
       status=date.toString(); 
       Log.d(LOGSERVICE,"my new time + = "+status); 

      // Log.d(LOGSERVICE,times); 
       Sender s=new Sender(getApplicationContext(),number,urlAddress,mlatitude,mlogtud,id,status); 
       s.execute(); 



      } 
     }; 
     timer=new Timer(); 
     timer.scheduleAtFixedRate(task,5*1000,8*1000); 
     wakeLock.release(); 


    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.i(LOGSERVICE, "onStartCommand"); 

     if (!mGoogleApiClient.isConnected()) 
      mGoogleApiClient.connect(); 

     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Log.d(LOGSERVICE,"servis destroy"); 
     timer.cancel(); 

    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     throw new UnsupportedOperationException("Not yet implemented"); 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     Log.i(LOGSERVICE, "onConnected" + bundle); 

     Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     if (l != null) { 
      Log.i(LOGSERVICE, "lat " + l.getLatitude()); 
      Log.i(LOGSERVICE, "lng " + l.getLongitude()); 


     } 

     startLocationUpdate(); 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     Log.i(LOGSERVICE, "onConnectionSuspended " + i); 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
      mlatitude = String.valueOf(location.getLatitude()); 
     mlogtud = String.valueOf(location.getLongitude()); 

     /* new Timer().schedule(new TimerTask() { 
      @Override 
      public void run() { 
      Sender s=new Sender(getApplicationContext(),number,urlAddress,mlatitude,mlogtud,id,status); 
       s.execute(); 

       Log.i(LOGSERVICE,"Location onnnn "); 
      } 
     },10*1000, 5*1000);*/ 
     LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude())); 
} 
    private void initLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(10000); 
     mLocationRequest.setFastestInterval(12000); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 

    } 
    private void startLocationUpdate() { 
     initLocationRequest(); 
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; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
    } 
    private void stopLocationUpdate() { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 

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

我的主要

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener { 
    protected static final int REQUEST_CHECK_SETTINGS = 0x1; 
    static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; 
    private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi; 
    private GoogleApiClient googleApiClient; 
    private LocationRequest locationRequest; 
    private static final String LOGSERVICE = "#######"; 
    Button btnStart, btnStop; 
    TextView textTime; 

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


     btnStart=(Button)findViewById(R.id.buttonStart) ; 
     btnStart.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       startService(new Intent(MainActivity.this,GpsService.class)); 

       Log.d(LOGSERVICE,"Starting Service"); 

      } 
     }); 
     btnStop=(Button)findViewById(R.id.buttonStop) ; 
     btnStop.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       stopService(new Intent(MainActivity.this,GpsService.class)); 
       Log.d(LOGSERVICE,"Stop Service"); 

      } 
     }); 



     googleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 

     locationRequest = new LocationRequest(); 
     locationRequest.setInterval(1000); 
     locationRequest.setFastestInterval(1000); 
     locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 



    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     requestLocationUpdates(); 

    } 

    private void requestLocationUpdates() { 


     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(MainActivity.this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 

      return; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 
    } 
    @Override 
    public void onRequestPermissionsResult(
      int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 

     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        Toast.makeText(MainActivity.this, 
          "permission was granted, :)", 
          Toast.LENGTH_LONG).show(); 
        requestLocationUpdates(); 
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 

       } else { 
        Toast.makeText(MainActivity.this, 
          "permission denied, ...:(", 
          Toast.LENGTH_LONG).show(); 
       } 
       return; 
      } 

      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 


    @Override 
    public void onConnectionSuspended(int i) { 


    } 
    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 
    @Override 
    public void onLocationChanged(Location location) { 
    /* Log.d(LOGSERVICE,"latitud" + location.getLatitude()); 
     Log.d(LOGSERVICE,"lotitude" + location.getLongitude()); 
     myLatitude = location.getLatitude(); 
     myLongitude = location.getLongitude(); 
     lat.setText(String.valueOf(myLatitude)); 
     lot.setText(String.valueOf(myLongitude));*/ 


    } 
    public void settingsrequest() 
    { 
     LocationRequest locationRequest = LocationRequest.create(); 
     locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     locationRequest.setInterval(1 * 1000); 
     locationRequest.setFastestInterval(1 * 1000); 
     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
       .addLocationRequest(locationRequest); 
     builder.setAlwaysShow(true); //this is the key ingredient 

     PendingResult<LocationSettingsResult> result = 
       LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); 
     result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
      @Override 
      public void onResult(LocationSettingsResult result) { 
       final Status status = result.getStatus(); 
       final LocationSettingsStates state = result.getLocationSettingsStates(); 
       switch (status.getStatusCode()) { 
        case LocationSettingsStatusCodes.SUCCESS: 
         // All location settings are satisfied. The client can initialize location 
         // requests here. 
         break; 
        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
         // Location settings are not satisfied. But could be fixed by showing the user 
         // a dialog. 
         try { 
          // Show the dialog by calling startResolutionForResult(), 
          // and check the result in onActivityResult(). 
          status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); 
         } catch (IntentSender.SendIntentException e) { 
          // Ignore the error. 
         } 
         break; 
        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
         // Location settings are not satisfied. However, we have no way to fix the 
         // settings so we won't show the dialog. 
         break; 
       } 
      } 
     }); 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch (requestCode) { 
// Check for the integer request code originally supplied to startResolutionForResult(). 
      case REQUEST_CHECK_SETTINGS: 
       switch (resultCode) { 
        case Activity.RESULT_OK: 
         requestLocationUpdates(); 
         Toast.makeText(getApplicationContext(),"Gps turn on",Toast.LENGTH_LONG).show(); 
         break; 
        case Activity.RESULT_CANCELED: 
         settingsrequest();//keep asking if imp or do whatever 
         break; 
       } 
       break; 
     } 
    } 


    @Override 
    protected void onStart() { 
     super.onStart(); 
     googleApiClient.connect(); 
     settingsrequest(); 



     Log.d(LOGSERVICE,"onSTart"); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     if (googleApiClient.isConnected()) { 
      requestLocationUpdates(); 
     } 
     Log.d(LOGSERVICE,"onResume"); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     // LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this); 
     Log.d(LOGSERVICE,"onPause"); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     // googleApiClient.disconnect(); 
     Log.d(LOGSERVICE,"onStop"); 
    } 

    @Override 
    protected void onDestroy() { 
     super.onDestroy(); 
     Log.d(LOGSERVICE,"onDestroy"); 
    } 
} 
+0

你可能會發現有趣的閱讀[打盹](https://developer.android.com/about/versions/nougat/android-7.0-changes.html#doze)這可能是你的情況,一些解決方案可能是[在優化應用程序的打盹](https://developer.android.com/training/monitoring-device-state/doze-standby.html#assessing_your_app)頁面 – AxelH

+0

這篇文章可能也有幫助https:// plus。 google.com/+AndroidDevelopers/posts/94jCkmG4jff –

+0

какэтоисправить? можешьмнепомочь?? – elik

回答

1

你做不正確使用Wakelock。

public void onCreate() { 
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); 
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
      "MyWakelockTag"); 

    super.onCreate(); 
    wakeLock.acquire(); 
    ... 
    task=new TimerTask() { 
     @Override 
     public void run() { 
      .... 
     } 
    }; 
    timer=new Timer(); 
    timer.scheduleAtFixedRate(task,5*1000,8*1000); 
    wakeLock.release(); 
} 

您正在釋放在onCreate方法結束鎖定,因此Task並無持有任何鎖的。只有在停止計劃任務時才應該釋放它。

請注意,在一些不活動之後忽略WakeLock的Doze的存在。

+0

這不是暫時打瞌睡,你只需釋放你想要保持它的鎖。但是你可以[調整應用](https://developer.android.com/training/monitoring-device-state/doze-standby.html#assessing_your_app)到Doze。 – AxelH

+0

好吧,先生,謝謝我現在嘗試 – elik

+0

理由打瞌睡? – elik