服务不发送数据

时间:2017-02-14 13:22:08

标签: java android

当屏幕被锁定打开和关闭时,服务停止向数据库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" );
    }
}

1 个答案:

答案 0 :(得分: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根本没有任何锁定。您应该在仅停止计划任务时释放它。

注意在注释中存在Doze,在一些不活动后忽略WakeLock。