2017-02-14 17 views
-1

を送信しないと、サービスはデータベースMysqlにデータを送信しなくなります。それを修正する方法私は答えを見つけることができない2日間、 が、これは私のコード厥 が起こっている理由を私に説明 をwakelockする権限を追加しました:?画面がロックされ、ロックされているときにサービスがデータ

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

あなたは[Doze](https://developer.android.com/about/versions/nougat/android-7.0-changes.html#doze)について読んで興味深いと思うかもしれませんが、これはあなたのケースかもしれませんし、解決策もいくつかあります[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を正しく使用しないでください。 Taskはまったくロックを保持していないので、

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方法の終わりにロックを解除しています。スケジュールされたタスクのみを停止するときには、それを解除する必要があります。

コメントには、一部の非アクティブ後にWakeLockを無視するDozeが存在することに注意してください。

+0

これは現時点ではDozeではありません。ロックを解除したい場所にロックを放すだけです。しかし、あなたは[アプリケーションを適応させる]ことができます(https://developer.android.com/training/monitoring-device-state/doze-standby.html#assessing_your_app)。 – AxelH

+0

お元気です。今すぐお試しください – elik

+0

理由doze ??? – elik

関連する問題