Boa noite, pessoal estou desenvolvendo um App Android que pega ( Latitude, longitude e Imei ) a cada 5 minutos e envia ao banco. até ai tudo certo, o service executa bem certinho quando o app está com a tela habilitada ou no caso está sendo utilizado, queria que o App mesmo com a tela bloqueada realize o serviço. foi criado um service, broadcastReceive.
Segue service
package com.example.junior.buskrastreamentogps;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class service extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
private Handler mHandler = new Handler();
// Creating Volley RequestQueue.
RequestQueue requestQueue;
// Create string variable to hold the EditText Value.
String ImeiHolder, LatitudeHolder,LongitudeHolder, tmpLat, tmpLon,tmpImei;
// ENDEREÇO DO SERVIDOR E PAGINA RESPONSAVEL POR RECEBER DADOS DO APP E INSERIR NO BANCO
String HttpUrl = "http://xxxxxxxx/inserir.php";
/** Called when the activity is first created. */
@TargetApi(Build.VERSION_CODES.O)
@Override
public void onCreate() {
super.onCreate();
Context context = getApplicationContext();
//NOTIFICAÇÃO PARA O USUARIO
String CHANNEL_ID = "my_channel_01";
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
// String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
//channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
PendingIntent p = PendingIntent.getActivity(this, 1, new Intent(this, service.class), 0);
notificationManager.createNotificationChannel(channel);
}else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo_busk)
.setContentTitle("Notificação")
.setContentText("Bem vindo")
.setPriority(NotificationCompat.PRIORITY_HIGH);
}
Log.d("TAG", "Serviço Criado, Notificação enviada");
Toast.makeText(service.this, "Proteção Criada", Toast.LENGTH_SHORT).show();
// Creating Volley newRequestQueue .
requestQueue = Volley.newRequestQueue(service.this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Comando Service inciado no OnStartComannd.");
Toast.makeText(service.this, "Proteção Incializada", Toast.LENGTH_SHORT).show();
Imei();
EnviarLocalizacao.run();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
Notification.Builder builder = new Notification.Builder(service.this,CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Notificação")
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(1, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this)
.setContentTitle(getString(R.string.app_name))
.setContentText("Notificação")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(1, notification);
}
return mStartMode;
}
private Runnable EnviarLocalizacao = new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void run() {
configurarServico();
//Toast.makeText(MainActivity.this, "This is a delayed toast", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(this, 180000);
}
};
private void Imei() {
final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
{
return;
}
@SuppressLint("HardwareIds") final String imei = telephonyManager.getDeviceId();
tmpImei = imei.toString();
ImeiHolder = tmpImei.trim();
}
public void configurarServico() {
try {
final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
double latPoint = location.getLatitude();
double lngPoint = location.getLongitude();
tmpLat = Double.toString(latPoint);
tmpLon = Double.toString(lngPoint);
LatitudeHolder = tmpLat.trim();
LongitudeHolder = tmpLon.trim();
insert_banco();
Imei();
Toast.makeText(service.this, "Proteção Sincronizada!", Toast.LENGTH_SHORT).show();
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener);
}catch(SecurityException ex){
//Toast.makeText(service.this, "Você precisa ativar a permissão do GPS", Toast.LENGTH_LONG).show();
}
}
public void insert_banco()
{
// Creating string request with post method.
StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String ServerResponse) {
// Showing response message coming from server.
//Toast.makeText(service.this, ServerResponse, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
// Showing error message if something goes wrong.
//Toast.makeText(service.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
// Creating Map String Params.
Map<String, String> params = new HashMap<String, String>();
// Adding All values to Params.
params.put("imei", ImeiHolder);
params.put("lat", LatitudeHolder);
params.put("lng", LongitudeHolder);
return params;
}
};
// Creating RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(service.this);
// Adding the StringRequest object into requestQueue.
requestQueue.add(stringRequest);
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TAG", "Serviço inciado no onStart.");
configurarServico();
}
//localização
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
}