Всем привет!Есть приложение которое отправляет данные на удаленную БД MySQL
.Все было прекрасно пока не начал тестировать в реальном времени ,вроде все и работает .но стоит свернуть приложение или поставить экран на блок то приложение перестает посылать данные на сервер.Почему ?Я сейчас выложу код прошу мне помочь.Я хочу понять когда телефон свернут он не определяет местоположение или не отправляет их .Или когда свернут вообще перестает функционировать.Как мне быть чтоб посоветовали?Спасибо всем.
Прошу вот мой кусок кода
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Double myLatitude;
private Double myLongitude;
....
Это мой onCreat в котором полученные данные посылаются через поток.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationRequest = new LocationRequest();
locationRequest.setInterval(10 * 1000);
locationRequest.setFastestInterval(15 * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
int i=0;
i++;
System.out.println("Request N +" +i);
Sender s=new Sender(MainActivity.this,urlAddress,lat,lot);
s.execute();
}
};
final Timer timer =new Timer();
Это слушатель после нажатия он через определенный интервал посылает данные в потоке .
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//timer.scheduleAtFixedRate(timerTask,0,3000);
timer.scheduleAtFixedRate(timerTask,0,8000);
}
});
}
Ну а вот и код получения
@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) {
Toast.makeText(getApplicationContext(),"Connect on",Toast.LENGTH_LONG).show();
// 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(googleApiClient, locationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
myLatitude = location.getLatitude();
myLongitude = location.getLongitude();
lat.setText(String.valueOf(myLatitude));
lot.setText(String.valueOf(myLongitude));
}
public Double getMyLatitude(){
return myLatitude;
}
public String getLong(){
return lot.getText().toString();
}
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();
settingsrequest();
googleApiClient.connect();
}
@Override
protected void onResume() {
super.onResume();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
@Override
protected void onPause() {
super.onPause();
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
@Override
protected void onStop() {
super.onStop();
googleApiClient.disconnect();
}
}
И вот мой Manifiest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Благодарю!