I'm implementing an app that It makes the search for ble devices connected, giving me back the mac address of the device. I have already found everything here: Android listing BLE devices after device scan or https://developer.android.com/guide/topics/connectivity/bluetooth-le.html
, the problem is that I want him in the background when open the activity called "track.java". I want that when you open the track activity, in the background you open the scanning process BLE and, when detected, it displays in a popup window. This is "Track.java"
package com.example.giacomob.myapplication;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by Giacomo B on 07/08/2015.
*/
public class Track extends FragmentActivity implements LocationListener {
private String providerId = LocationManager.GPS_PROVIDER;
private LocationManager locationManager=null;
private static final int MIN_DIST=20;
private static final int MIN_PERIOD=30000;
int maxrows=8;
float distance = 0;
/*
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
*/
GPSTracker gps;
double newLatitude;
double newLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//////////////mi sa che questi non servno
/* double currentLat = 51.43376;
double currentLng = -2.86221;
double destLat = 51.43503;
double destLng = -2.86869;
Location here = new Location("Current");
here.setLatitude(currentLat);
here.setLongitude(currentLng);
Location dest = new Location("Destination2");
dest.setLatitude(destLat);
dest.setLongitude(destLng);
Log.d("GPS", "Bearing to dest: " + here.bearingTo(dest));
Log.d("GPS", "Distance to dest: " + here.distanceTo(dest));
*/
String dato1 = getIntent().getExtras().getString("Destination"); //preleva la stringa
int position = getIntent().getExtras().getInt("Posizione");
//int position = position1-(position1%maxrows)+1;
// if(position1%maxrows==0)
// position = position1-1;
//else
String paese = getIntent().getExtras().getString("Paese");
System.out.println("La posizione è"+position);
// System.out.println("Il paese è"+paese);
String[] arr = dato1.split("\\|");
int countc = 0;
int paesi = 0;
for(int i =3; i<arr.length;i=i+maxrows){
if(arr[i].equals(paese)){
paesi++;
}
}
String[] coord = new String[paesi*2];
for(int i =3; i<arr.length;i=i+maxrows){
if(arr[i].equals(paese)){
coord[countc]= arr[i-3];
countc++;
coord[countc]= arr[i-2];
countc++;
}
}
//------------- da questo punto in poi implementerò il ciclo che mi dia le coordinate x e y esatte scelte dall'utente
int x=0,y=0;
boolean stop = false;
for (int k=1,q=0; stop == false; k++,q=q+2 )
if((position%((maxrows+2)*k) == 0) && (k==1)){ //+2 perchè rispetto al file dell xml abbiamo due righe inpiù, una per il pulsante ed una per la distanza
x=q;
y=q+1;
stop = true;
}
else if ((position%(((maxrows+2)*k)+(k-1)) == 0) && (k!=1)){ //+2 perchè rispetto al file dell xml abbiamo due righe inpiù, una per il pulsante ed una per la distanza
x=q;
y=q+1;
stop = true;
}
System.out.println("x vale "+x+" y vale "+y);
//---------- fine ciclo
/*
for(int i =0; i<arr.length;i++) {
System.out.println("Questa è la stringa coord" + coord[i]);
}
*/
/*String[] coordinate;//////////////////////////////////////////////////////////////////////voglio fare in modo che mi passi solo le coordinate col paese
for(int k=0; k<arr.length; k++)
for(int j=0+k; j<c*8+3; j++){
if(arr[k]==paese) {
coordinate[j] = arr[k-2]
}
}
*/
//map.setMyLocationEnabled(true);
// centra la mappa su CENTER_POINT, con zoom 5
try
{
// find actual position
gps = new GPSTracker(Track.this);
if (gps.canGetLocation()) {
newLatitude = gps.getLatitude();
newLongitude = gps.getLongitude();
// check if GPS enabled
/* while(newLatitude ==0 && newLongitude ==0) { //While aggiunto da me
// Toast.makeText(getBaseContext(), "Attendi", Toast.LENGTH_SHORT).show();
}*/ if(newLatitude != 0 && newLongitude !=0) {
for (int delay = 0; delay < 5; delay++) { //moltiplico per 5 la durata del toast
Toast.makeText(getBaseContext(), "lat : " + newLatitude + "long : " + newLongitude + "/n Per cambiare modalita' percorso (mezzo/piedi) clicca sulla destinazione", Toast.LENGTH_SHORT).show();
}
}
//////////////////////
final LatLng CENTER_POINT=new LatLng(newLatitude, newLongitude);
GoogleMap map=((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER_POINT, 5));
/////////////////////
//++++++++++++++++++++++++
if(newLatitude == 0 && newLongitude ==0) {
Toast.makeText(getBaseContext(), "GPS non disponibile, necessario attivare la rete dati.", Toast.LENGTH_SHORT).show();
// NavUtils.navigateUpTo(this,
// new Intent(this, Page1.class));
// Intent openPage1 = new Intent(Track.this, Page1.class);
// startActivity(openPage1);
}
else {///////////////////////////////////////////// è qui che al posto di arr[0] e arr[1], metterò il numero corrispondente alla riga scelta+posizione delle coordinate*8
String uri = String.format("http://maps.google.com/maps?f=d&saddr=%1$s,%2$s&daddr=%3$s,%4$s &hl=en", newLatitude, newLongitude, coord[x], coord[y]);
// String uri = String.format("http://maps.google.com/maps?f=d&saddr=%1$s,%2$s&daddr=%3$s,%4$s &hl=en", newLatitude, newLongitude, coord[0], coord[1]);
//http://maps.google.com/maps?f=d&saddr=Cannole&daddr=Lecce WA&hl=en
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
i.setComponent(new ComponentName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"));
startActivity(i);
Intent searchBLE = new Intent(Track.this, LogService.class);
startActivity(searchBLE);
}
//++++++++++++++++++++++++
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
System.out.println("On Resume");
/*
if (!locationManager.isProviderEnabled(providerId))
{
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}*/
super.onResume();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(providerId))
{
System.out.println("is Provider Enabled");
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
else {
System.out.println("no Provider Enabled");
locationManager.requestLocationUpdates(providerId, MIN_PERIOD, MIN_DIST, this);
}
/* new CountDownTimer(5000, 1000) { // 5000 = 5 sec
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Intent searchBLE = new Intent(Track.this, LogService.class);
startActivity(searchBLE);
}
}.start();
*/
}
private void updateGUI(Location location)
{
System.out.println("updateGUI");
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="Ci troviamo in coordinate ("+latitude+","+longitude+")";
TextView txt= (TextView) findViewById(R.id.locationText);
System.out.println(msg);
txt.setText(msg);
}
@Override
protected void onPause()
{
System.out.println("On Pause");
super.onPause();
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location)
{
System.out.println("On location changed");
updateGUI(location);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle)
{ }
@Override
public void onProviderEnabled(String s)
{ }
@Override
public void onProviderDisabled(String s)
{ }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
can someone help me? Thanks, I'm desperate