Java BLE在Android的后台工作
我正在实现一个应用程序,它可以搜索连接的ble设备,并返回设备的mac地址。我已经在这里找到了一切: 或 ,问题是当打开名为“track.java”的活动时,我希望他在后台。我希望当你打开track活动时,在后台打开扫描过程,当检测到时,它会显示在弹出窗口中。 这是“Track.java”Java BLE在Android的后台工作,java,android,service,background,bluetooth,Java,Android,Service,Background,Bluetooth,我正在实现一个应用程序,它可以搜索连接的ble设备,并返回设备的mac地址。我已经在这里找到了一切: 或 ,问题是当打开名为“track.java”的活动时,我希望他在后台。我希望当你打开track活动时,在后台打开扫描过程,当检测到时,它会显示在弹出窗口中。 这是“Track.java” package com.example.giacomob.myapplication; 导入android.content.ActivityNotFoundException; 导入android.cont
package com.example.giacomob.myapplication;
导入android.content.ActivityNotFoundException;
导入android.content.ComponentName;
导入android.content.Context;
导入android.content.Intent;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.net.Uri;
导入android.os.Bundle;
导入android.support.v4.app.FragmentActivity;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.google.android.gms.maps.CameraUpdateFactory;
导入com.google.android.gms.maps.GoogleMap;
导入com.google.android.gms.maps.SupportMapFragment;
导入com.google.android.gms.maps.model.LatLng;
/**
*由Giacomo B于2015年8月7日创建。
*/
公共类Track扩展FragmentActivity实现LocationListener{
私有字符串providerId=LocationManager.GPS\U提供程序;
专用LocationManager LocationManager=null;
专用静态最终整数最小距离=20;
私有静态最终整数最小周期=30000;
int maxrows=8;
浮动距离=0;
/*
//初始化蓝牙适配器。
最终BluetoothManager BluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH\u服务);
mBluetoothAdapter=bluetoothManager.getAdapter();
*/
全球定位系统;
双新纬度;
双经度;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_轨迹);
this.locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
//////////////我不知道该怎么办
/*双电流LAT=51.43376;
双电流lng=-2.86221;
双脱层=51.43503;
双destLng=-2.86869;
此处位置=新位置(“当前”);
此处为设置纬度(currentLat);
此处。设置经度(currentLng);
地点目的地=新地点(“目的地2”);
目的地设置纬度(目的地纬度);
目的地设定经度(destLng);
日志d(“GPS”,“指向目的地:+此处。指向目的地”);
Log.d(“GPS”,“到目的地的距离:”+此处。距离(目的地));
*/
字符串dato1=getIntent().getExtras().getString(“目的地”);//preleva la stringa
int position=getIntent().getExtras().getInt(“Posizione”);
//int位置=位置1-(位置1%maxrows)+1;
//如果(位置1%maxrows==0)
//位置=位置1-1;
//否则
字符串paese=getIntent().getExtras().getString(“paese”);
System.out.println(“La posizioneè”+位置);
//System.out.println(“Il paeseè”+paese);
字符串[]arr=dato1.split(“\\\\”);
int countc=0;
int-paesi=0;
对于(int i=3;iread asynctask)进行后台工作。@RandykaYudhistira“asynctask被设计为围绕线程和处理程序的助手类,并不构成通用线程框架。AsyncTasks理想情况下应用于短操作(最多几秒钟)。”但我想一直使用操作,而不是几秒钟
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);
}
}