I'm new on this and I don't know how I can print on the mobile phone the RSSI that I have scanned before. This is my code, tell me please what I'm making wrong.
I have to send this for a final project and I can't see the Rssi.
public class MainActivity extends AppCompatActivity {
//declare
private BluetoothAdapter mBluetoothAdapter;
private final static int REQUEST_ENABLE_BT = 1;
private BluetoothLeScanner mBluetoothLeScanner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
//start and stop scan
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
// Checks if Bluetooth LE Scanner is available.
if (mBluetoothLeScanner == null)
{
Toast.makeText(this, "Can Not Find BLE Scanner", Toast.LENGTH_SHORT).show();
finish();
return;
}
}
public class DeviceScanActivity extends ListActivity {
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private android.os.Handler mHandler;
// Stops scanning after 10 seconds (10000).
private static final long SCAN_PERIOD = 1000;
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanning = false;
mBluetoothLeScanner.stopScan((ScanCallback) mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
mScanning = true;
mBluetoothLeScanner.startScan((ScanCallback) mLeScanCallback);
} else
{
mScanning = false;
mBluetoothLeScanner.stopScan((ScanCallback) mLeScanCallback);
}
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
TextView SwitchOff = (TextView) findViewById(R.id.txonoff);
SwitchOff = (TextView) findViewById(R.id.txonoff);
SwitchOff.getText();
SwitchOff.setText("Potència= " + rssi + "dBm\n");
}
});
}
};
};
Related
I am working on BLE devices android application. i am trying to get available bluetooth devices using scanCallBack. It was working fine some days ago but suddenly it stopped. onScanResults or onScanFailed nothing are NOT executing. I have given the ACCESS_COARSE_LOCATION, BLUETOOTH_ADMIN, BLUETOOTH and ACCESS_FINE_LOCATION in manifest and request permissions at run time also.Bluetooth is on and location is also on. Please help.
Measurement.java
public class MeasurementScreen extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
static int REQUEST_ENABLE_BT = 1001;
private Boolean spinnerStatus= false;
private Handler handler = new Handler(Looper.getMainLooper());
final BluetoothAdapter mBluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_reading_screen);
Objects.requireNonNull(getSupportActionBar()).hide();
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck == -1 ) {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION
}, 0);
}
}
final Button tryAgain = findViewById(R.id.tryagain);
next = findViewById(R.id.next);
back = findViewById(R.id.back);
progressDialog = new ProgressDialog(this);
bluetoothscan();
}
void bluetoothscan(){
spinner();
scanBLEDevices(true);
}
private void scanBLEDevices(final boolean enable){
final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
final BLEScanCallback scanCallback = new BLEScanCallback();
if (enable){
// Stops scanning after a pre-defined scan period.
handler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}, 10000);
mScanning = true;
bluetoothLeScanner.startScan(scanCallback);
}else{
mScanning = false;
bluetoothLeScanner.stopScan(scanCallback);
}
}
public class BLEScanCallback extends ScanCallback{
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
Log.e("Scan Success", "Scan Success");
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
Log.e("Scan Success", "Scan Success Batch");
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("Scan Failed", "Error Code: " + errorCode);
}
}
}
This is the log output:-
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6
mClientIf=0
Basically, I am an iOS developer. I have a requirement to scan, connect & disconnect BLE devices. Everything works fine in iOS. Then I tried the following code to scan in Android. None of the devices re scanned at anytime. Could anyone help me, if I am doing something wrong.
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
TextView statusTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusTextView = (TextView)findViewById(R.id.statusTxtView);
}
#Override
protected void onStart() {
super.onStart();
enableBluetooth();
}
private void enableBluetooth() {
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
statusTextView.setText("BT disabled");
Intent enableBtIntent =
new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
} else {
statusTextView.setText("BT enabled");
}
boolean status = bluetoothAdapter.startDiscovery();
if (status == true) {
statusTextView.setText("Start scanning");
} else {
statusTextView.setText("Failed scanning");
}
}
BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
statusTextView.setText(device.getName());
}
};
}
You've not started scanning. After starting bluetooth discovery using bluetoothAdapter.startDiscovery(), you have to start scanning in order to get scan results. Use the following code to start scan.
I've not tested it but it should work as follows:
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
scanner.startScan(scanCallback);
where scanCallback is the above callback you have created but unused.
Make sure that you have BLUETOOTH_ADMIN permission.
First you have to scan device
#SuppressLint("NewApi")
private void turnonBLE() {
// TODO Auto-generated method stub
manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
mBLEAdapter = manager.getAdapter();
mLeScanner = mBLEAdapter.getBluetoothLeScanner();
mBLEAdapter.enable();
scanLeDevice(true);
Toast.makeText(getApplicationContext(), "BTLE ON Service",
Toast.LENGTH_LONG).show();
Log.e("BLE_Scanner", "TurnOnBLE");
}
If you are not using any uuid then scan without uuid
public void scanLeDevice(final boolean enable) {
if (enable) {
if (Build.VERSION.SDK_INT < 21) {
mBLEAdapter.startLeScan(mLeScanCallback);
} else {
ParcelUuid uuid = ParcelUuid.fromString(UUIDList.SENSOR_MAIN_SERVICE_UUID_STRING.toString());
ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(uuid).build();
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0)
.build();
if (mLeScanner != null)
mLeScanner.startScan(Collections.singletonList(scanFilter), settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBLEAdapter.stopLeScan(mLeScanCallback);
} else {
mLeScanner.stopScan(mScanCallback);
}
}
}
From that call scanCallback
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice btDevice = result.getDevice();
connectToDevice(btDevice, result.getScanRecord().getBytes());
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
Log.e("ScanResult - Results", sr.toString());
}
}
#Override
public void onScanFailed(int errorCode) {
Log.e("Scan Failed", "Error Code: " + errorCode);
}
};
for connect device call gattCallback
private synchronized void connectToDevice(BluetoothDevice device, byte[] scanRecord) {
mGatt = device.connectGatt(getApplicationContext(), false, mBtGattCallback);
}
private BluetoothGattCallback mBtGattCallback = new BluetoothGattCallback() {
// override all methods
}
I have an Arduino code driven ESP32 chip.
For Android code, it setup a callback for connection attempt
mGatt = device.connectGatt(this, false, gattCallback, TRANSPORT_LE );
but
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback()
do not happen.
However, from Arduino side, it does see a connected happen and start to send data out. ESP32 also blink connected LED.
Any idea what was wrong?
SDK version is 26,
minSDK is 23,
targetSDK is 23,
run on Samsung Galaxy S7
thanks a lot!
#TargetApi(21)
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private BluetoothGatt mGatt;
private TextView line_1, line_2, line_3, line_4;
private ImageButton btnTrash, btnEmail;
private UUID uuid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uuid = UUID.fromString("8dc99748-0ad4-11e8-ba89-0ed5f89f718b");
line_1 = (TextView) findViewById(R.id.textLine1);
line_2 = (TextView) findViewById(R.id.textLine2);
line_3 = (TextView) findViewById(R.id.textLine3);
line_4 = (TextView) findViewById(R.id.textLine4);
mHandler = new Handler();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE Not Supported",
Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
line_3.setText("" + status);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
line_1.setText(" connected ");
Toast.makeText(getApplicationContext()," connected ", Toast.LENGTH_LONG);
// gatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
Log.e("gattCallback", "STATE_DISCONNECTED");
break;
default:
Log.e("gattCallback", "STATE_OTHER");
}
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
List<BluetoothGattService> services = gatt.getServices();
line_1.setText(" server discover");
gatt.readCharacteristic(services.get(1).getCharacteristics().get
(0));
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic
characteristic, int status) {
Log.i("onCharacteristicRead", characteristic.toString());
gatt.disconnect();
}
#Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic)
{
line_1.setText(" charactertics changed");
}
};
#Override
protected void onResume() {
super.onResume();
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= 21) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
}
scanLeDevice(true);
}
}
#Override
protected void onPause() {
super.onPause();
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
scanLeDevice(false);
}
}
#Override
protected void onDestroy() {
if (mGatt == null) {
return;
}
mGatt.close();
mGatt = null;
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_CANCELED) {
//Bluetooth not enabled.
finish();
return;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
// mLEScanner.startScan(filters, settings, mScanCallback);
}
}
}, SCAN_PERIOD);
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
line_1.setText(" mLEScanner ");
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else {
if (Build.VERSION.SDK_INT < 21) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
BluetoothDevice btDevice = result.getDevice();
line_2.setText("try connect to " + btDevice.getName());
connectToDevice(btDevice);
}
#Override
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult sr : results) {
line_2.setText(" batch scan result");
}
}
#Override
public void onScanFailed(int errorCode) {
line_2.setText("scan fail");
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("onLeScan", device.toString());
connectToDevice(device);
}
});
}
};
public void connectToDevice(BluetoothDevice device) {
if (mGatt == null) {
try {
BluetoothSocket temp = device.createRfcommSocketToServiceRecord(uuid);
mGatt = device.connectGatt(this, false, gattCallback, TRANSPORT_LE );
} catch( Exception e)
{
}
line_3.setText( device.getAddress());
line_4.setText( "device type: "+ device.getType());
scanLeDevice(false);// will stop after first device detection
}
}
}
My app needs to connect to a Bluetooth Low Energy device, and obviously the first step is to detect it. I have written the code bellow to do just that. When I run the app I have another BLE device (Xperia M2) beside my Dev phone (Huawei P8 Lite) with Bluetooth ON and discoverable, however, nothing get printed on the logcat. Is the device truly not being discovered or is the callback function not being called/malfunctioning. What can I do to identify which one of this situations is happening?
The scanBluetoothMethod is called elsewhere in the code.
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner scanner;
private Handler scanHandler = new Handler();
private List<ScanFilter> scanFilters = new ArrayList<ScanFilter>();
private ScanSettings scanSettings;
private boolean scanRunning=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_pandlet);
...
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
private void scanBluetoothLE() {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
return;
}
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.addpandlet_searchingforbledevices));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(true);
progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, getString(R.string.addpandlet_cancelsearch), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scanner.stopScan(scanCallback);
scanHandler.removeCallbacks(scanRunnable);
scanRunning = false;
return;
}
});
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
//scanSettingsBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
scanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
scanSettings = scanSettingsBuilder.build();
scanHandler.post(scanRunnable);
}
private Runnable scanRunnable = new Runnable() {
#Override
public void run() {
scanner = BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner();
if (scanRunning) {
scanner.stopScan(scanCallback);
progressDialog.hide();
scanRunning = false;
} else {
scanRunning = true;
progressDialog.show();
scanHandler.postDelayed(this, SCAN_PERIOD);
scanner.startScan(scanFilters, scanSettings, scanCallback);
}
}
};
private ScanCallback scanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
System.out.println(result.getRssi() + " " + result.getDevice().getName() );
super.onScanResult(callbackType, result);
}
#Override
public void onScanFailed(int errorCode) {
System.out.println("Error code " + errorCode );
super.onScanFailed(errorCode);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK )
scanBluetoothLE();
}
From the code - BluetoothAdapter.getDefaultAdapter().getBluetoothLeScanner(); it seems you are trying to scan bluetooth low energy devices..The device you are using I guess supports only classic bluetooth.
Try using devices which advertise bluetooth low energy services.You can build a app which advertise ble services on a device which supports bluetooth low energy.
Just to be sure, you can go to Settings->bluetooth and scan to check whether the device is being discovered by the default device bluetooth module.
Also you can check whether the device is detected by some other standard apps on playstore-https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp&hl=en
I have a service class and I fetch data from an Intent in the method "onHandleIntent" and pick up in a variable. I would to call the value of this variable in onCreate, but when I call this variable I get a NULL value. (for examole in onHandleIntent i have a variable a = True, but in onCreate this variable is not true). I would to take this variable from onHandleIntent to onCreate. This is my code:
public class LogService extends IntentService
{
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
SoundManager sm;
private boolean notifica = false;
private String id;
Boolean a = false;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 2100000000;
Handler handler;
public LogService()
{
super("LogService");
}
#Override
protected void onHandleIntent(Intent intent) {
id=(String) intent.getStringExtra("idc");
System.out.println("id1 e'" + id);
a = true;
}
#Override
public void onCreate() {
// ActiveBluetooth();
handler = new Handler();
super.onCreate();
// super.onCreate(savedInstanceState);
mHandler = new Handler();
System.out.println("Vero o falso?'" + a);
System.out.println("id e'" + id);
// Boolean a = getIntent().getExtras().getBoolean("ok");
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivities(enableBtIntent, REQUEST_ENABLE_BT);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
super.onDestroy();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
super.onDestroy();
return;
}
// Checks if Bluetooth is supported on the device.
//onResume();
// BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
/* if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Auto attivazione blueooth: Bluetooth attivato.", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.enable();
scanLeDevice(true);
Intent refresh = new Intent(LogService.this, LogService.class);
startService(refresh);
// Intent refresh = new Intent(this, LogService.class);
//startService(refresh);
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
}*/
// if (!mBluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// ab.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//}
scanLeDevice(true);
}
/*
protected void onResume() {
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
scanLeDevice(true);
}*/
private void scanLeDevice(final boolean enable) {
if (!mBluetoothAdapter.isEnabled() && notifica == false) {
Toast.makeText(this, "Auto attivazione blueooth: Bluetooth attivato.", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.enable();
stopService(new Intent(this, LogService.class));
startService(new Intent(this, LogService.class));
}
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.i("Trovato", "Evento n.");
System.out.println("TROVATO");
notifica = true;
notifica(device.getAddress());
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
//System.out.println(device.getAddress());
onDestroy();
// mBluetoothAdapter.stopLeScan(mLeScanCallback);
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
};
#Override
public void onDestroy()
{
Log.i("PROVA SERVICE", "Distruzione Service");
System.out.println("Distruzione");
// mScanning = false;
// mBluetoothAdapter.stopLeScan(mLeScanCallback); //� stato invocato il metodo onDestroy(), posso fermare la scansione
super.onDestroy();
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
private void notifica(String a) {
Log.i("Trovato", "Evento n.");
System.out.println("VAAAAAAAAA");
System.out.println("Indirizzo dispositivo" + a);
NotificationCompat.Builder n = new NotificationCompat.Builder(this);
// n.setLargeIcon(Imag);
n.setContentInfo("Affrettati!");
n.setContentTitle("La corriera e' in arrivo!");
n.setContentText(a);
n.setSmallIcon(R.drawable.bus);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
sm.init(LogService.this);
sm.play();
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Toast.makeText(this, "Auto disattivazione blueooth: Bluetooth disattivato.", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.disable();
super.onDestroy();
}
}
Can someone help me? Thanks
mHandler = new Handler();
mHandler.onHandleIntent(Intent Var);
yes , when load your class .on create is the first run that method . so ,not initialized 'onHandleIntent' method.so , you call that method , within on create method.I think this will solve your problem.
note : you pass 'Intent' object as a parameter.
example :
Intent i = new Intent(LogService.this);
mHandler = new Handler();
mHandler.onHandleIntent(i);