Intento lanzar un activity cuando el teléfono esta bloqueado y veo que se lanza muchas veces seguidas, pero cuando se lanza con la pantalla encendida funciona normal, tengo api 23, probé con apis anteriores y esto no sucede ¿Que debo hacer para que Start Activity se lance una sola vez sin importar que el teléfono este bloqueado?
Intent dialogIntent = new Intent(MyService.this, MapsActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//escritor="4";
Bander2="2";
SharedPreferences contra = getSharedPreferences("", MODE_PRIVATE);
SharedPreferences.Editor editor1 = contra.edit();
editor1.putString("Contraseña", String.valueOf(ACTIVO));
editor1.commit();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
text2 = (TextView) findViewById(R.id.tvDistance);
text3 = (TextView) findViewById(R.id.tvDuration);
text1 = (TextView) findViewById(R.id.text1);
SharedPreferences cedula = getSharedPreferences("", MODE_PRIVATE);
ced = cedula.getString("Usuario", "");
Toolbar toolbar = (Toolbar) findViewById(R.id.to);
setSupportActionBar(toolbar);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.buttonFollow);
on = spref.getBoolean("On", true); //default is true
if (on == true) {
tb.setChecked(true);
tb.setBackgroundColor(0xffcc0000);
} else {
tb.setChecked(false);
tb.setBackgroundColor(Color.BLUE);
}
notificacion = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
AlertNoGps();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
} else {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
MostrarLocalizacion(location);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MostrarLocalizacion(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 0, locationListener);}
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, locationListener);
}
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void carrera(int id, int iconid, String titulo, String contenido) {
Intent intent = new Intent(this, MapsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contIntent = PendingIntent.getActivity(MapsActivity.this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(iconid)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),
R.mipmap.poder_amarillo))
.setContentTitle(titulo)
.setContentIntent(contIntent)
.setSound((Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.vip)))
.setVibrate(new long[]{ 1000,500,1000,800,1000,1500 })
.setLights(Color.RED,3000,3000)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(Notification.PRIORITY_MAX)
.setContentText(contenido);
notificacion.notify(id, builder.build());
}
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
tb.setBackgroundColor(0xffcc0000);
escritor = "4";
resp = "2";
Toast.makeText(getApplicationContext(), "Su estado ha cambiado a ocupado!!!" ,Toast.LENGTH_SHORT).show();
send();
} else {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
text2.setText(null);
text3.setText(null);
text1.setText(null);
resp = "0";
tb.setBackgroundColor(Color.BLUE);
escritor = "4";
Toast.makeText(getApplicationContext(), "Su estado ha cambiado a disponible!!!", Toast.LENGTH_SHORT).show();
mMap.clear();
X = "0";
Y = "0";
send();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void send (){
hiloconexion = new obtenerwebservice();
hiloconexion.execute(String.valueOf(escritor),String.valueOf(ced),String.valueOf(ACTIVO),String.valueOf(lat),String.valueOf(lon),String.valueOf(resp),String.valueOf(TIME));
}
private void sendRequest() {
String origin = String.valueOf(lat)+","+String.valueOf(lon);
String destination = Y+","+X;
try {
new DirectionFinder(this, origin, destination).execute();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
@Override
public void onDirectionFinderStart() {
progressDialog = ProgressDialog.show(this, "Espere por favor",
"Obteniendo ruta!", true);
if (originMarkers != null) {
for (Marker marker : originMarkers) {
marker.remove();
}
}
if (destinationMarkers != null) {
for (Marker marker : destinationMarkers) {
marker.remove();
}
}
if (polylinePaths != null) {
for (Polyline polyline:polylinePaths ) {
polyline.remove();
}
}
}
public void MostrarLocalizacion(Location loc) {
if(ACTIVO == "0"){
loc = null;
}
if (loc != null) {
hiloconexion = new obtenerwebservice(); hiloconexion.execute(String.valueOf(escritor),String.valueOf(ced),String.valueOf(ACTIVO),String.valueOf(loc.getLatitude()),String.valueOf(loc.getLongitude()),String.valueOf(resp),String.valueOf(TIME));
}
}
public void servicio() {
hiloconexion = new obtenerwebservice();
hiloconexion.execute("2", String.valueOf(ced), String.valueOf(ACTIVO), String.valueOf(lat), String.valueOf(lon), String.valueOf(resp), String.valueOf(TIME));
}
@Override
public void onDirectionFinderSuccess(List<Route> routes) {
progressDialog.dismiss();
polylinePaths = new ArrayList<>();
originMarkers = new ArrayList<>();
destinationMarkers = new ArrayList<>();
for (Route route : routes) {
text2.setText(route.distance.text);
text3.setText(route.duration.text);
TIME = text3.getText().toString();
send();
/*originMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.poder_amarillo))
.title(route.startAddress)
.position(route.startLocation)));*/
destinationMarkers.add(mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.poder_amarillo))
.title(route.endAddress)
.position(route.endLocation)));
PolylineOptions polylineOptions = new PolylineOptions().
geodesic(true).
color(Color.BLUE).
width(8);
for (int i = 0; i < route.points.size(); i++)
polylineOptions.add(route.points.get(i));
polylinePaths.add(mMap.addPolyline(polylineOptions));
}
}
public void alertcar(){
Bander = "0";
builder= new AlertDialog.Builder(this);
builder.setMessage("Dirección: " + comentario +" ¿Desea aceptar el servicio?")
.setCancelable(false);
builder.setPositiveButton("SI", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
text1.setText(comentario);
resp="4";
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
tb.setChecked(true);
tb.setText("ocupado");
tb.setBackgroundColor(0xffcc0000);
escritor = "4";
Toast.makeText(getApplicationContext(), "Su estado ha cambiado a ocupado!!!" ,Toast.LENGTH_SHORT).show();
Bander = "1";
notificacion.cancelAll();
sendRequest();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
text1.setText(null);
resp="3";
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
tb.setChecked(true);
tb.setText("ocupado");
tb.setBackgroundColor(0xffcc0000);
escritor = "4";
Bander = "1";
Toast.makeText(getApplicationContext(), "Su estado ha cambiado a ocupado!!!" ,Toast.LENGTH_SHORT).show();
mMap.clear();
X = "0";
Y = "0";
notificacion.cancelAll();
send();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void Exit (){
ACTIVO="0";
SharedPreferences contra = getSharedPreferences("",MODE_PRIVATE);
SharedPreferences.Editor editor1 = contra.edit();
editor1.putString("Contraseña",String.valueOf(ACTIVO));
editor1.commit();
hiloconexion = new obtenerwebservice();
hiloconexion.execute(String.valueOf(escritor),String.valueOf(ced),String.valueOf(ACTIVO),"0","0",String.valueOf(resp));
servicio();
}
private ProgressDialog pDialog;
public void Zaliendo(){
builder= new AlertDialog.Builder(this);
builder.setMessage("¿Desea salir de la aplicación?");
builder.setPositiveButton("SI", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Exit();
pDialog = new ProgressDialog(MapsActivity.this);
pDialog.setMessage("Desconectando del servidor...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK) {
Zaliendo();
}
return super.onKeyDown(keyCode, event);
}
public class obtenerwebservice extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
int devuelve =0;
URL url = null;
String cade = "http://186.183.210.220/actualizar_alumno.php";
String cadena ="http://186.183.210.220/obtener_alumno_por_id.php?username="+ced;
String caden = "http://186.183.210.220/myservice.php";
while (Bander2 == "2") {
if (params[0] == "4") {
try {
HttpURLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL(cade);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("username", params[1]);
jsonParam.put("activo", params[2]);
jsonParam.put("latitud", params[3]);
jsonParam.put("longitud", params[4]);
jsonParam.put("servicio", params[5]);
jsonParam.put("tiempo", params[6]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();
int respuesta = urlConn.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = br.readLine()) != null) {
result.append(line);
//response+=line;
}
//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados
int resultJSON = respuestaJSON.getInt("estado"); // estado es el nombre del campo en el JSON
if (resultJSON == 1) {
devuelve = 4;
} else if (resultJSON == 2) {
devuelve = 4;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
escritor = "3";
return String.valueOf(devuelve);
} else if (params[0] == "2") { // consulta por id
try {
url = new URL(cadena);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
" (Linux; Android 1.5; es-ES) Ejemplo HTTP");
//connection.setHeader("content-type", "application/json");
int respuesta = connection.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(connection.getInputStream()); // preparo la cadena de entrada
BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // la introduzco en un BufferedReader
// El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
// que tranformar el BufferedReader a String. Esto lo hago a traves de un
// StringBuilder.
String line;
while ((line = reader.readLine()) != null) {
result.append(line); // Paso toda la entrada al StringBuilder
}
//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados
int resultJSON = respuestaJSON.getInt("estado");
if (resultJSON == 1) { // hay un alumno que mostrar
devuelve = respuestaJSON.getJSONObject("users").getInt("servicio");
Z = respuestaJSON.getJSONObject("users").getInt("latitud");
Log.i("mensaje", String.valueOf(Z));
if (Prim == 1) {
if (Z == 0) {
Intent intent = new Intent(MapsActivity.this, Login.class);
startActivity(intent);
finish();
System.exit(0);
}
}
Prim = 1;
if (devuelve == 1) {
Y = respuestaJSON.getJSONObject("users").getString("lat");
X = respuestaJSON.getJSONObject("users").getString("lon");
comentario = respuestaJSON.getJSONObject("users").getString("comentario");
}
} else if (resultJSON == 2) {
devuelve = 2;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return String.valueOf(devuelve);
} else if (params[0] == "3") {
try {
HttpURLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL(caden);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("username", params[1]);
jsonParam.put("activo", params[2]);
jsonParam.put("latitud", params[3]);
jsonParam.put("longitud", params[4]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();
int respuesta = urlConn.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = br.readLine()) != null) {
result.append(line);
}
//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString());
int resultJSON = respuestaJSON.getInt("estado"); // estado es el nombre del campo en el JSON
if (resultJSON == 1) {
devuelve = 4;
} else if (resultJSON == 2) {
devuelve = 4;
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
servicio();
return String.valueOf(devuelve);
}
}
return "5";
}
@Override
protected void onCancelled(String aVoid) {
super.onCancelled(aVoid);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String aVoid) {
int numero = 0;
numero = Integer.parseInt(aVoid);
if (1 == numero) {
if (escritor == "3"){
if (Bander=="1"){
carrera(1,R.mipmap.poder_amarillo,"Taxis VIP","Actualmente tiene un servicio");
alertcar();}
}
}else if ( numero == 4){
Log.i("GPSactivi", aVoid);
//Toast.makeText(getApplicationContext(), "Envio del Activity", Toast.LENGTH_SHORT).show();
}
//super.onPostExecute(aVoid);
}
}
@Override
protected void onDestroy() {
//.makeText(getApplicationContext(), "Destruida" ,Toast.LENGTH_SHORT).show();
//notificacion.cancelAll();
super.onDestroy();
}
@Override
protected void onResume() {
//Toast.makeText(getApplicationContext(), "pausa" ,Toast.LENGTH_SHORT).show();
Bander ="1";
stopService(new Intent(MapsActivity.this, MyService.class));
this.mWakeLock.acquire();
Bander2 ="2";
servicio();
super.onResume();
}