BLE Scanner only shows one record - java

I am working on a Bluetooth Scanner in android studio. I am still learning so i'm terribly sorry for all the rooky mistakes. I had it working a while ago, but couldn't get the UUID from a device. So I searched and searched and finally I had something working. But now the problem is that there is only one BLE device after a scan. The list doesn't expand. If I use another scanning app I'm finding multiple devices. Your help would be much appreciated and any feedback on my rooky code is more then welcome! PS: please know that i used some code I've found online, so if there is anything useless or really weird, please inform me..
public class Scanner_BTLE {
private MainActivity ma;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private long scanPeriod;
private int signalStrength;
public Scanner_BTLE(MainActivity mainActivity, long scanPeriod, int signalStrength) {
ma = mainActivity;
mHandler = new Handler();
this.scanPeriod = scanPeriod;
this.signalStrength = signalStrength;
final BluetoothManager bluetoothManager =
(BluetoothManager) ma.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
final int new_rssi = rssi;
int startByte = 2;
boolean patternFound = false;
while (startByte <= 5) {
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && //Identifies an iBeacon
((int) scanRecord[startByte + 3] & 0xff) == 0x15) { //Identifies correct data length
patternFound = true;
break;
}
startByte++;
}
if (patternFound) {
//Convert to hex String
byte[] uuidBytes = new byte[16];
System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
String hexString = bytesToHex(uuidBytes);
//UUID detection
final String uuid = hexString.substring(0, 8) + "-" +
hexString.substring(8, 12) + "-" +
hexString.substring(12, 16) + "-" +
hexString.substring(16, 20) + "-" +
hexString.substring(20, 32);
// major
final int major = (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);
// minor
final int minor = (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);
if (rssi > signalStrength) {
mHandler.post(new Runnable() {
#Override
public void run() {
ma.addDevice(device, new_rssi, scanRecord, major, minor, uuid);
}
});
}
}
}
}
;
public boolean isScanning() {
return mScanning;
}
public void start() {
if (!Utils.checkBluetooth(mBluetoothAdapter)) {
Utils.requestUserBluetooth(ma);
ma.stopScan();
} else {
scanLeDevice(true);
}
}
public void stop() {
scanLeDevice(false);
}
// If you want to scan for only specific types of peripherals,
// you can instead call startLeScan(UUID[], BluetoothAdapter.LeScanCallback),
// providing an array of UUID objects that specify the GATT services your app supports.
private void scanLeDevice(final boolean enable) {
if (enable && !mScanning) {
Utils.toast(ma.getApplicationContext(), "Starting BLE scan...");
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Utils.toast(ma.getApplicationContext(), "Stopping BLE scan...");
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
ma.stopScan();
}
}, scanPeriod);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
}
BTLE_DEVICE
public class BTLE_Device {
private BluetoothDevice bluetoothDevice;
private int rssi;
private String uuid;
private int major;
private int minor;
public BTLE_Device(BluetoothDevice bluetoothDevice) {
this.bluetoothDevice = bluetoothDevice;
}
public void setRSSI(int rssi) {
this.rssi = rssi;
}
public int getRSSI() {
return rssi;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getMajor() {
return major;
}
public void setMajor(int major) {
this.major = major;
}
public int getMinor() {
return minor;
}
public void setMinor(int minor) {
this.minor = minor;
}
}
LIST ADAPTER (no idea if i'm doing this right :) )
public class ListAdapter_BTLE_Devices extends ArrayAdapter<BTLE_Device> {
Activity activity;
int layoutResourceID;
ArrayList<BTLE_Device> devices;
public ListAdapter_BTLE_Devices(Activity activity, int resource, ArrayList<BTLE_Device> objects) {
super(activity.getApplicationContext(), resource, objects);
this.activity = activity;
layoutResourceID = resource;
devices = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater) activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutResourceID, parent, false);
}
BTLE_Device device = devices.get(position);
String rssi = String.valueOf (device.getRSSI());
String major = String.valueOf (device.getMajor());
String minor = String.valueOf (device.getMinor ());
String uuid = device.getUuid ();
TextView tv_major = (TextView)convertView.findViewById (R.id.tv_major);
TextView tv_minor = (TextView)convertView.findViewById (R.id.tv_minor);
TextView tv_uuid = (TextView)convertView.findViewById (R.id.tv_uuid);
TextView tv_rssi = (TextView)convertView.findViewById (R.id.tv_rssi);
tv_major.setText (major);
tv_minor.setText (minor);
tv_uuid.setText (uuid);
tv_rssi.setText (rssi);
return convertView;
}
}
And finally my Main Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
//INITIALIZE VARIABLES
private final static String TAG = MainActivity.class.getSimpleName ( );
public static final int REQUEST_ENABLE_BT = 1;
private HashMap <String, BTLE_Device> mBTDevicesHashMap;
private ArrayList <BTLE_Device> mBTDevicesArrayList;
private ListAdapter_BTLE_Devices adapter;
private Button btn_addIncident;
private Button btn_Scan;
private Button btn_incidentlist;
private Button btn_scanMyBeacon;
private BroadcastReceiver_BTState mBTStateUpdateReceiver;
private Scanner_BTLE mBTLeScanner;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 456;
private Realm realm;
#Override
//ONCREATE
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//CHECK IF BL IS SUPPORTED ON DEVICE
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Utils.toast(getApplicationContext(), "BLE not supported");
finish();
}
//REQUEST PERIMISSIONS ( BLUETOOTH & GPS )
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
//INITIALIZE
mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext());
mBTLeScanner = new Scanner_BTLE(this, 7500, -105);
mBTDevicesHashMap = new HashMap<>();
mBTDevicesArrayList = new ArrayList<>();
adapter = new ListAdapter_BTLE_Devices(this, R.layout.btle_device_list_item, mBTDevicesArrayList);
ListView listView = new ListView(this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
((ScrollView) findViewById(R.id.scrollView)).addView(listView);
//BUTTONS TO VARIABLE
btn_scanMyBeacon = (Button) findViewById(R.id.btn_scanMyBeacon);
btn_Scan = (Button) findViewById(R.id.btn_scan);
btn_incidentlist = (Button) findViewById(R.id.btn_incident_list_sort);
btn_addIncident = (Button) findViewById(R.id.btn_addIncident);
//ONCLICKLISTENERS
btn_Scan.setOnClickListener(this);
btn_scanMyBeacon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startScan();
}
});
btn_incidentlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent listIntent = new Intent(MainActivity.this,IncidentListActivity.class);
MainActivity.this.startActivity(listIntent);
}
});
btn_addIncident.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Add_Incident.class);
MainActivity.this.startActivity(myIntent);
}
});
//REALM
try {
realm = Realm.getDefaultInstance ( ); // opens "myrealm.realm"
}
catch (Exception e) {
RealmConfiguration config = new RealmConfiguration.Builder ()
.deleteRealmIfMigrationNeeded ()
.build ();
realm.getInstance (config);
}
}
#Override
//ONSTART
protected void onStart() {
super.onStart();
registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
#Override
//ONRESUME
protected void onResume() {
super.onResume();
}
#Override
//ONPAUSE
protected void onPause() {
super.onPause();
stopScan();
}
#Override
//ONSTOP
protected void onStop() {
super.onStop();
unregisterReceiver(mBTStateUpdateReceiver);
stopScan();
}
#Override
//ONDESTROY
public void onDestroy() {
super.onDestroy();
realm.close();
}
#Override
//BLUETOOTH CHECK
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Utils.toast(getApplicationContext(), "Thank you for turning on Bluetooth");
} else if (resultCode == RESULT_CANCELED) {
Utils.toast(getApplicationContext(), "Please turn on Bluetooth");
}
}
}
#Override
//ONCLICK SCAN BUTTON
public void onClick(View v) {
//Called when the scan button is clicked. v= clicked view
switch (v.getId()) {
case R.id.btn_scan:
Utils.toast(getApplicationContext(), "Scan Button Pressed");
if (!mBTLeScanner.isScanning()) {
startScan();
} else {
stopScan();
}
break;
default:
break;
}
}
//ADD DEVICE
/**
* Adds a device to the ArrayList and Hashmap that the ListAdapter is keeping track of.
*
* #param device the BluetoothDevice to be added
* #param rssi the rssi of the BluetoothDevice
*/
public void addDevice(BluetoothDevice device, int rssi, byte[] scanRecord, int major, int minor, String uuid) {
Log.d ("first add","Device"+ device.getAddress ()+"rssi" +rssi+"uuid"+uuid );
Log.d("HashMap",""+mBTDevicesHashMap.size());
Log.d("ArrayList",""+mBTDevicesArrayList.size());
if (!mBTDevicesHashMap.containsKey(uuid)) {
BTLE_Device btleDevice = new BTLE_Device(device);
btleDevice.setRSSI(rssi);
mBTDevicesHashMap.put(uuid, btleDevice);
mBTDevicesArrayList.add(btleDevice);
} else {
BTLE_Device current = mBTDevicesHashMap.get(uuid);
current.setRSSI(rssi);
current.setMajor(major);
current.setMinor(minor);
current.setUuid(uuid);
}
Log.d("HashMapAfter",""+mBTDevicesHashMap.size());
Log.d("ArrayListAfter",""+mBTDevicesArrayList.size());
adapter.notifyDataSetChanged();
}
//START SCAN
/**
* Clears the ArrayList and Hashmap the ListAdapter is keeping track of.
* Starts Scanner_BTLE.
* Changes the scan button text.
*/
public void startScan() {
btn_Scan.setText("Scanning...");
mBTDevicesArrayList.clear();
mBTDevicesHashMap.clear();
adapter.notifyDataSetChanged();
mBTLeScanner.start();
}
//STOP SCAN
/**
* Stops Scanner_BTLE
* Changes the scan button text.
*/
public void stopScan() {
btn_Scan.setText("Scan Again");
mBTLeScanner.stop();
for(int i=0; i<mBTDevicesArrayList.size();i++){
System.out.println (mBTDevicesArrayList.get(i).getUuid() );
}
}
/**
* Called when an item in the ListView is clicked.
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println ( );
}
}

Jesper, you are sure that next to you there are several devices that meet the bottom condition
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 &&
((int) scanRecord[startByte + 3] & 0xff) == 0x15)

Related

BLE image transfer

Here is the code to convert an image to byte array and and send to ble device
i am not able to send complete data and its stopping nearly at 1kb
what are the methods to send large data to ble .
will it be appropriate to use delay in the data transfer and if so can you share the code
if anyone has any code to send data upto 1mb please do share
public class RxTxActivity extends Activity {
byte[] imageInByte,SendByte;
private static int IMG_RESULT = 1;
String ImageDecode;
ImageView imageViewLoad;
Button LoadImage;
Intent intent;
String[] FILE;
String[] SAImage,SAsent;
private final static String TAG = DeviceControlActivity.class.getSimpleName();
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
private TextView mCharaDescriptor;
private TextView mConnectionState;
private TextView mDataField;
private TextView mDeviceAddressTextView;
private String mServiceUUID, mDeviceAddress;
private String mCharaUUID, mDeviceName;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = true;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private Button EditButton;
private Button CharaSubscribeButton;
private EditText EditText;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private String CHARA_DESC = "";
private String properties = "";
private Context context = this;
// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a result of read
// or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case BluetoothLeService.ACTION_GATT_CONNECTED:
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_DISCONNECTED:
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
break;
case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED:
break;
case BluetoothLeService.ACTION_DATA_AVAILABLE:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data Received!", Toast.LENGTH_SHORT).show();
}
});
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
break;
case BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE:
Log.i("Receiving data", "Broadcast received");
displayDescriptor(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
default:
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_transfer);
imageViewLoad = (ImageView) findViewById(R.id.imageView1);
LoadImage = (Button)findViewById(R.id.button1);
LoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMG_RESULT);
}
});
final Intent intent = getIntent();
Log.i("OnCreate", "Created");
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mServiceUUID = intent.getStringExtra("Service UUID");
mCharaUUID = intent.getStringExtra("Characteristic UUID");
CHARA_DESC = intent.getStringExtra("Characteristic Descriptor");
properties = intent.getStringExtra("Characteristic properties");
// Sets up UI references.
((TextView) findViewById(R.id.device_address_rxtx)).setText("Characteristic UUID: " + mCharaUUID);
((TextView) findViewById(R.id.characteristic_Descriptor)).setText("Characteristic Descriptor: " + CHARA_DESC);
((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
mConnectionState = (TextView) findViewById(R.id.connection_state);
mConnectionState.setText("Connected");
mDataField = (TextView) findViewById(R.id.data_value);
EditText = (EditText) findViewById(R.id.characteristicEditText);
EditButton = (Button) findViewById(R.id.characteristicButton);
CharaSubscribeButton = (Button) findViewById(R.id.characteristic_Subscribe);
mCharaDescriptor = (TextView) findViewById(R.id.characteristic_Descriptor);
EditButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = EditText.getText().toString();
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Message Sent!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
CharaSubscribeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (properties.indexOf("Indicate") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 1);
} else if (properties.indexOf("Notify") >= 0) {
mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 2);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Characteristic Subscribed!", Toast.LENGTH_SHORT).show();
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
});
checkProperties();
getActionBar().setTitle(mDeviceName);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
private void checkProperties() {
if (properties.indexOf("Write") >= 0) {
} else {
EditButton.setEnabled(false);
}
if (properties.indexOf("Indicate") >= 0) {
} else {
CharaSubscribeButton.setEnabled(false);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
final boolean result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.gatt_services, menu);
if (mConnected) {
menu.findItem(R.id.menu_connect).setVisible(false);
menu.findItem(R.id.menu_disconnect).setVisible(true);
} else {
menu.findItem(R.id.menu_connect).setVisible(true);
menu.findItem(R.id.menu_disconnect).setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_connect:
mBluetoothLeService.connect(mDeviceAddress);
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mConnectionState.setText(resourceId);
}
});
}
private void displayData(String data) {
if (data != null) {
mDataField.setText(data);
}
}
private void displayDescriptor(final String data) {
if( data != null){
runOnUiThread(new Runnable() {
#Override
public void run() {
mCharaDescriptor.setText(mCharaDescriptor.getText().toString() + "\n" + data);
}
});
}
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE);
return intentFilter;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == IMG_RESULT && resultCode == RESULT_OK
&& null != data) {
Uri URI = data.getData();
String[] FILE = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(URI,
FILE, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(FILE[0]);
ImageDecode = cursor.getString(columnIndex);
cursor.close();
imageViewLoad.setImageBitmap(BitmapFactory
.decodeFile(ImageDecode));
}
} catch (Exception e) {
Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
.show();
}
}
public void ClickConvert(View view) {
TextView txtView;
txtView=(TextView)findViewById(R.id.textview_byte);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
String response ;
response = byteArrayToString(imageInByte);
// response = new sun.misc.BASE64Encoder().encode(imageInByte);
//String s = javax.xml.bind.DatatypeConverter.printHexBinary(imageInByte);
//String str = new String(imageInByte, "UTF-8");
txtView.setText(response);
}
public static String byteArrayToString(byte[] data){
String response = Arrays.toString(data);
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
return str.toLowerCase();
}
public void ClickImage(View view) {
final int num= imageInByte.length;
int i,j,l,h;
j=num/20;
Toast.makeText(getApplicationContext(), "loop : " + j, Toast.LENGTH_SHORT).show();
for (i = 0; i <= j; i++) {
l=20*i;
h=20*(i+1);
SystemClock.sleep(40); //ms
SendByte = Arrays.copyOfRange(imageInByte, l, h);
String str = new String(SendByte);
mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
}
}
}
Here is the code for writecustomCharacteristics
public void writeCustomCharacteristic(String str, String serviceUuid, String charaUuid) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
/*check if the service is available on the device*/
BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(serviceUuid));
if(mCustomService == null){
Log.w(TAG, "Custom BLE Service not found");
return;
}
/*byte[] value = parseHex(str);
*//*get the read characteristic from the service*//*
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);*/
byte[] strBytes = str.getBytes();
BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
mWriteCharacteristic.setValue(strBytes);
mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);
}

Google Cloud Speech API for Android

Currently I`m working on a project where i have to use Google Cloud Speech Api and TextToSpeech. I try-ed to work around with RecognizerIntent but i would like to give a try to Cloud Speech .
Would be great some tutorial material or guide , i checked the sample app
but i`m looking for tutorial , guide anything that could explain something.
Here is my work around with TTS and RecognizerIntent .
private TextToSpeech tts;
private TextToSpeech secondTTS;
private TextView speechInputTextView,correctAnswerTextView,wrongAnswerTextView,currentQuestionTextView;
private ArrayList<String> correctAnswersArrayList, questionArrayList, sayCorrectArrayList, sayWrongArrayList ,toSay ,toASk;
private MediaPlayer mediaPlayer;
private DBHelper dbHelper;
private SQLiteDatabase sqlDB;
private int correctACount,wrongACount,currentQuestion, Unit;
private boolean isStarted;
private String currentLanguage ;
private static int TOTAL_QUESITONS;
private final static int REQ_CODE_SPEECH_INPUT = 100;
private final static String PAUSE_COMMAND = "pos";
private final static String STOP_COMMAND = "stop";
private final static String RESTART_COMMNAD = "restart";
private final static String REPEAT_COMMAND = "repeat";
private final static String EXIT_COMMAND = "exit";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unit);
isStarted = true;
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.unitonemp3);
currentQuestion = 0;
speechInputTextView = (TextView) findViewById(R.id.speechInput);
correctAnswerTextView = (TextView) findViewById(R.id.correctAnswers_TextView);
currentQuestionTextView = (TextView) findViewById(R.id.currentQuestion_TextView);
wrongAnswerTextView = (TextView) findViewById(R.id.wrongAnswer_TextView);
Unit = 1;
currentLanguage = getIntent().getBundleExtra("resultBundle").getString("language");
Button next = (Button) findViewById(R.id.nextButton);
Button changeUnitButton = (Button) findViewById(R.id.changeUnitButton);
Button playButton = (Button) findViewById(R.id.playButton);
Button pauseButton = (Button) findViewById(R.id.pauseButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
}
});
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts.stop();
secondTTS.stop();
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
}
});
tts = new TextToSpeech(this, this);
secondTTS = new TextToSpeech(this, this);
changeUnitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
secondTTS.stop();
tts.stop();
Unit ++;
mediaPlayer.start();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
currentQuestion = getIntent().getBundleExtra("resultBundle").getInt("npc");
}
ImageView micButton = (ImageView) findViewById(R.id.micButton);
micButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!tts.isSpeaking()) {
currentQuestion = 13;
startSayWithID(questionArrayList.get(currentQuestion), 1000, "questionID");
}
}
});
String[] sayCorrectList = getResources().getStringArray(R.array.sayCorrect);
String[] sayWrongList = getResources().getStringArray(R.array.satWrong);
String[] listToSay = getResources().getStringArray(R.array.toSay);
String[] listToAsk = getResources().getStringArray(R.array.toAsk);
toSay = new ArrayList<>(Arrays.asList(listToSay));
toASk = new ArrayList<>(Arrays.asList(listToAsk));
questionArrayList = new ArrayList<>();
correctAnswersArrayList = new ArrayList<>();
addGerCorrect();
addEngQuestions();
sayCorrectArrayList = new ArrayList<>(Arrays.asList(sayCorrectList));
sayWrongArrayList = new ArrayList<>(Arrays.asList(sayWrongList));
TOTAL_QUESITONS = questionArrayList.size();
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startSayWithID("Welcome",1000,"instruction");
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0 ; i< questionArrayList.size();i++){
Log.d(" question List "," item :"+"pisition "+i+ "" +questionArrayList.get(i));
}
currentQuestion++;
tts.stop();
secondTTS.stop();
startSayWithID("",1000,"instruction");
}
});
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (utteranceId.contains("say")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ", "current Question" + currentQuestion + "" + correctAnswersArrayList.get(currentQuestion));
}else
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
}
if (utteranceId.contains("instruction")) {
if (correctAnswersArrayList.get(currentQuestion).contains("tensa23")) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "say");
currentQuestion++;
Log.d("Current ","current Question"+currentQuestion +""+correctAnswersArrayList.get(currentQuestion));
} else if (questionArrayList.get(currentQuestion).contains("?")) {
startSayWithID(toASk.get(new Random().nextInt(toASk.size())), 1000, "say");
} else {
startSayWithID(toSay.get(new Random().nextInt(toSay.size())), 1000, "say");
}
}
if (utteranceId.contains("question")) {
if(questionArrayList.get(currentQuestion).contains("?")){
startSayWithID("in Spanish you ask",1000,"german");
}else{
startSayWithID("In Spanish you say",1000,"german");
}
}
if (utteranceId.contains("german")) {
secondTTS.speak(correctAnswersArrayList.get(currentQuestion),TextToSpeech.QUEUE_FLUSH,null,"ask");
}
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
secondTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(final String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(utteranceId.contains("ask")){
startAsk(1000);
}
}
});
}
#Override
public void onError(String utteranceId) {
}
});
// end of MainActivity
}
private void promptSpeechInput() {
Intent prompIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
prompIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-ES");
prompIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "How do you say \n" +questionArrayList.get(currentQuestion));
try {
startActivityForResult(prompIntent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
makeText(getApplicationContext(), "speech not supported", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
switch (currentLanguage){
case "Spanish" :
secondTTS.setLanguage(new Locale("es","Es"));
break;
case "Italian" :
secondTTS.setLanguage(Locale.ITALY);
break;
case "German" :
secondTTS.setLanguage(Locale.GERMAN);
break;
case "French" :
secondTTS.setLanguage(Locale.FRENCH);
break;
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
speechInputTextView.setText(result.get(0));
}
}
String inputSpeechToString = speechInputTextView.getText().toString().toLowerCase();
if (currentQuestion < TOTAL_QUESITONS && inputSpeechToString.contains(correctAnswersArrayList.get(currentQuestion))) {
currentQuestion++;
correctACount++;
correctAnswerTextView.setText(String.valueOf(correctACount));
currentQuestionTextView.setText(String.valueOf(currentQuestion));
Log.d("Onactivity ", "CurrentQ = " + currentQuestion);
startSayWithID(sayCorrectArrayList.get(new Random().nextInt(sayCorrectArrayList.size())), 1000, "instruction");
} else if (inputSpeechToString.contains(STOP_COMMAND)) {
Intent stopIntent = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putBoolean("isStarted", isStarted);
stopIntent.putExtra("resultBundle", resultBundle);
startActivity(stopIntent);
} else if (inputSpeechToString.contains(PAUSE_COMMAND)) {
Intent pauseI = new Intent(UnitActivity.this, PauseActivity.class);
Bundle resultBundle = new Bundle();
resultBundle.putInt("npc", currentQuestion);
pauseI.putExtra("resultBundle", resultBundle);
startActivity(pauseI);
} else if (inputSpeechToString.contains(RESTART_COMMNAD)) {
currentQuestion = 0;
startSayWithID("Restarted", 1000, "say");
} else if (inputSpeechToString.contains(REPEAT_COMMAND)) {
startSayWithID(questionArrayList.get(currentQuestion), 1000, "question");
} else if (inputSpeechToString.contains(EXIT_COMMAND)) {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
} else {
startSayWithID(sayWrongArrayList.get(new Random().nextInt(sayWrongArrayList.size())), 1000, "instruction");
wrongACount++;
wrongAnswerTextView.setText(String.valueOf(wrongACount));
Log.d("Onactivity ", "CORRECT = " + correctAnswersArrayList.get(currentQuestion));
Log.d("Onactivity ", "You said : " + inputSpeechToString);
}
}
}
private void addEngQuestions() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryEngQuestion = "SELECT English FROM " +currentLanguage+ " WHERE " + "Unit = " +Unit+ " ORDER BY Unit ASC";
Cursor cursor = sqlDB.rawQuery(queryEngQuestion, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
questionArrayList.add(cursor.getString(cursor.getColumnIndex("English")));
cursor.moveToNext();
}
} finally {
cursor.close();
}
Log.d("Line 255", " English Arraylist" + questionArrayList.size());
}
private void addGerCorrect() {
dbHelper = new DBHelper(this);
sqlDB = dbHelper.getReadableDatabase();
String queryGerCOrrect = "SELECT "+ currentLanguage +" FROM "+ currentLanguage + " WHERE "+ "Unit = "+Unit+ " ORDER BY Unit ASC";
Cursor cursor2 = sqlDB.rawQuery(queryGerCOrrect, null);
try {
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
correctAnswersArrayList.add(cursor2.getString(cursor2.getColumnIndex(currentLanguage))
.replaceAll("\\p{P}", "").toLowerCase());
cursor2.moveToNext();
}
} finally {
cursor2.close();
}
}
private void startSayWithID(final String text, int mSeconds, final String ID) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, ID);
}
}, mSeconds);
}
private void startAsk(int seconds) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
promptSpeechInput();
}
}, seconds);
}
#Override
protected void onDestroy() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (secondTTS != null) {
secondTTS.stop();
secondTTS.shutdown();
}
super.onDestroy();
}
Setting up Google Speech cloud on Android is not a straightforward 1,2,3 process, but I will give you some guidance.
Download the Sample project from here, use the Speech example.
https://github.com/GoogleCloudPlatform/android-docs-samples/tree/master/speech/Speech
Setup a google cloud project, enable the Speech API, and link it to
your gmail account's billing (you get 60min of free speech recognition
every month).
Generate an authentication json, and put it into the "raw" folder of
the sample project.
Setup Google cloud on your computer and obtain an access token.
Insert that access token on your SpeechService.java class.
*Documentation on steps 3 and 4:
https://cloud.google.com/speech/docs/getting-started
*If you run into problems when trying to mimic the sample project into your own project, check this:
Cannot import com.google.cloud.speech.v1.SpeechGrpc in Android
The exact steps are too long to list, I can't even remember them all, if you run into specific trouble let me know.

Regarding issue on App Lock Service Android

I am working for App Locker. I have made services that will check locked apps and will show LOCK APP SCREEN so that user can enter password code. My code is working fine till this stage when Lock App open.
I need to stop my service because my service is continuously running? It is showing my Login Activity again and again while user has already enter correct credentials. How can I stop this issue?
code:
Service:
public class ProcessService extends Service {
private Set<String> mLockedApps = new HashSet<String>();
private long lastModified = 0;
private BroadcastReceiver mScreenStateReceiver;
private File mLockedAppsFile;
ArrayList<String> packagezList;
SharedPreferences sharedPrefs;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
Object obj;
private String prefix;
private Handler handler;
private DbAccess dbAccess;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startService(new Intent(this, ProcessService.class));
dbAccess=new DbAccess(this);
if (TIMER == null) {
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 3000, 750);
mScreenStateReceiver = new BroadcastReceiver() {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
if (screenOff) {
//Log.i(TAG, "Cancel Timer");
TIMER.cancel();
} else {
// Log.i(TAG, "Restart Timer");
TIMER = new Timer(true);
TIMER.scheduleAtFixedRate(new LockAppsTimerTask(), 1000, 250);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenStateReceiver, filter);
}
// this.stopSelf();
//startforeground goes here
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
startService(new Intent(this, ProcessService.class));
}
private class LockAppsTimerTask extends TimerTask {
#Override
public void run() {
sharedPrefs = getApplicationContext().getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
sharedPrefsapp = getApplicationContext().getSharedPreferences("appdb", Context.MODE_PRIVATE);
allEntries= null;
allEntries = sharedPrefsapp.getAll();
//prefix = "m";
packagezList= null;
packagezList = new ArrayList<String>();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.e("right key: ", entry.getKey().toString() + "right value: " + entry.getValue().toString());
packagezList.add(entry.getKey());
}
for(Object object: packagezList){
Log.e("Object!", (String) object);
// Log.e("Package",""+packagezList.get(0));
}
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
try {
//List<RecentTaskInfo> recentTasks = activityManager.getRecentTasks(1, ActivityManager.RECENT_IGNORE_UNAVAILABLE);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
Log.e("activity on Top", "" + activityOnTop);
Log.e(" My package name", "" + getApplicationContext().getPackageName());
//for (Object data : newArrayList) {
for(Object object: packagezList){
Log.e("My Object!", (String)object);
if(activityOnTop.equals("com.android.settings"))
{ // you have to make this check even better
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
i.putExtra("callFromService",true);
i.putExtra("ApppakageName", "com.android.settings" );
startActivity(i);
}
}
} catch (Exception e) {
Log.e("Foreground App", e.getMessage(), e);
}
}
}
}
LockScreenActivity:
public class SeconActivity extends Activity {
public static final String TAG = "AppLock-Abhishek";
private String oldPasscode = null;
protected EditText codeField1 = null;
protected EditText codeField2 = null;
protected EditText codeField3 = null;
protected EditText codeField4 = null;
protected TextView tvMessage = null;
protected InputFilter[] filters = null;
private String str1,str2,str3,str4;
private ProgressDialog dialog;
Map<String, ?> allEntries;
SharedPreferences sharedPrefsapp;
ArrayList<String> packagezList;
private DbAccess dbAccess;
private ActionBar actionBar;
private int type=0;
private String confirmPass=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbAccess=new DbAccess(this);
dialog=new ProgressDialog(this);
setContentView(R.layout.page_passcode);
Cursor c;
c=dbAccess.getType();
if(c.moveToNext())
type=c.getInt(c.getColumnIndex("type"));
Cursor cursor;
cursor=dbAccess.getPasssword();
if (cursor.moveToNext()) {
confirmPass = cursor.getString(cursor.getColumnIndex("password"));
}
tvMessage = (TextView) findViewById(R.id.tv_message);
tvMessage.setText(R.string.reenter_passcode);
//editcodeFields
filters = new InputFilter[2];
filters[0] = new InputFilter.LengthFilter(1);
filters[1] = numberFilter;
codeField1 = (EditText) findViewById(R.id.passcode_1);
setupEditText(codeField1);
codeField2 = (EditText) findViewById(R.id.passcode_2);
setupEditText(codeField2);
codeField3 = (EditText) findViewById(R.id.passcode_3);
setupEditText(codeField3);
codeField4 = (EditText) findViewById(R.id.passcode_4);
setupEditText(codeField4);
// setup the keyboard
((Button) findViewById(R.id.button0)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button1)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button2)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button3)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button4)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button5)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button6)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button7)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button8)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button9)).setOnClickListener(btnListener);
((Button) findViewById(R.id.button_clear))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
clearFields();
}
});
((Button) findViewById(R.id.button_erase))
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onDeleteKey();
}
});
}
private InputFilter numberFilter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source.length() > 1) {
return "";
}
if (source.length() == 0) // erase
{
return null;
}
try {
int number = Integer.parseInt(source.toString());
if ((number >= 0) && (number <= 9))
return String.valueOf(number);
else
return "";
} catch (NumberFormatException e) {
return "";
}
}
};
protected void reEnterePass()
{
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
// set the value and move the focus
}
protected void onPasscodeError() {
Toast toast = Toast.makeText(this, getString(R.string.passcode_wrong),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 30);
toast.show();
Thread thread = new Thread() {
public void run() {
Animation animation = AnimationUtils.loadAnimation(
SeconActivity.this, R.anim.shake);
findViewById(R.id.ll_applock).startAnimation(animation);
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.requestFocus();
}
};
runOnUiThread(thread);
}
protected void setupEditText(EditText editText) {
editText.setInputType(InputType.TYPE_NULL);
editText.setFilters(filters);
editText.setOnTouchListener(touchListener);
editText.setTransformationMethod(PasswordTransformationMethod
.getInstance());
}
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.performClick();
clearFields();
return false;
}
};
private void clearFields() {
codeField1.setText("");
codeField2.setText("");
codeField3.setText("");
codeField4.setText("");
codeField1.postDelayed(new Runnable() {
#Override
public void run() {
codeField1.requestFocus();
}
}, 200);
}
private View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int currentValue = -1;
int id = view.getId();
if (id == R.id.button0) {
currentValue = 0;
} else if (id == R.id.button1) {
currentValue = 1;
} else if (id == R.id.button2) {
currentValue = 2;
} else if (id == R.id.button3) {
currentValue = 3;
} else if (id == R.id.button4) {
currentValue = 4;
} else if (id == R.id.button5) {
currentValue = 5;
} else if (id == R.id.button6) {
currentValue = 6;
} else if (id == R.id.button7) {
currentValue = 7;
} else if (id == R.id.button8) {
currentValue = 8;
} else if (id == R.id.button9) {
currentValue = 9;
} else {
}
// set the value and move the focus
String currentValueString = String.valueOf(currentValue);
if (codeField1.isFocused()) {
codeField1.setText(currentValueString);
str1=currentValueString;
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField2.isFocused()) {
codeField2.setText(currentValueString);
str2=currentValueString;
codeField3.requestFocus();
codeField3.setText("");
} else if (codeField3.isFocused()) {
codeField3.setText(currentValueString);
str3=currentValueString;
codeField4.requestFocus();
codeField4.setText("");
} else if (codeField4.isFocused()) {
codeField4.setText(currentValueString);
str4=currentValueString;
}
if (codeField4.getText().toString().length() > 0
&& codeField3.getText().toString().length() > 0
&& codeField2.getText().toString().length() > 0
&& codeField1.getText().toString().length() > 0) {
Log.e(TAG, str1 + str2 + str3 + str4);
String passCode=(str1+str2+str3+str4).trim();
switch (type){
case 1:
if (passCode.equals(confirmPass)){
startActivity(new Intent(getApplicationContext(),LockScreenActivity.class));
}else
{
onPasscodeError();
}
break;
case 2:
if(passCode.equalsIgnoreCase(confirmPass)){
finish();
}else
{
Intent startHomescreen=new Intent(Intent.ACTION_MAIN);
startHomescreen.addCategory(Intent.CATEGORY_HOME);
startHomescreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(startHomescreen);
}
break;
default:
break;
}
}
}
};
private void onDeleteKey() {
if (codeField1.isFocused()) {
} else if (codeField2.isFocused()) {
codeField1.requestFocus();
codeField1.setText("");
} else if (codeField3.isFocused()) {
codeField2.requestFocus();
codeField2.setText("");
} else if (codeField4.isFocused()) {
codeField3.requestFocus();
codeField3.setText("");
}
}
}//end of class
First of all I would like to tell you that you should not rely on Timer for your code to run repetitively because timer is destroyed by system after sometime , i hope u would have realized this bug. And for your problem you should create a hashmap to know weather the foreground activity is already accessed by user or not by verifying the password.

Android MediaPlayer cannot play files that contain '#' character in the file name using Uri.parse(path)

From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.

Running Bluetooth as background service not working properly

*I am new in android any help please help me and thanks in advance.
I want that bluetooth is always connected in app while switching from one activity to another. so I am making background service . There are two classes first class shows the list of paired device and second class is used to run the bluetooth as background service . There is no error Everything is fine but when I switch the activity Bluetooth is disconnected and also it didn't show the status changed. Ask me If you need any additional information *
This is my first class Homescreen class
public class Homescreen extends Activity {
public static Homescreen home;
private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;
private BluetoothAdapter mBTAdapter;
private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;
private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)
private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
home=this;
ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
Log.d(TAG, "Created");
mBtnSearch = (Button) findViewById(R.id.btnSearch);
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mLstDevices = (ListView) findViewById(R.id.lstDevices);
/*
*Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
*like screen rotate etc. If that's the case then populate all the views that are necessary here
*/
if (savedInstanceState != null) {
ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
if(list!=null){
initList(list);
MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
if(selectedIndex != -1){
adapter.setSelectedIndex(selectedIndex);
mBtnConnect.setEnabled(true);
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
mBtnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
} else if (!mBTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, BT_ENABLE_REQUEST);
} else {
new SearchDevices().execute();
}
}
});
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intt=new Intent(Homescreen.this,BluetoothService.class);
//bindService( intt, null, Context.BIND_AUTO_CREATE);
BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
intt.putExtra(DEVICE_EXTRA, device);
intt.putExtra(DEVICE_UUID, mDeviceUUID.toString());
intt.putExtra(BUFFER_SIZE, mBufferSize);
startService(intt);
// Toast.makeText(Homescreen.this, "Device Connected", Toast.LENGTH_LONG).show();
// BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
// Intent intent = new Intent(getApplicationContext(), MainBluetooth.class);
// intent.putExtra(DEVICE_EXTRA, device);
// intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
// intent.putExtra(BUFFER_SIZE, mBufferSize);
// startActivity(intent);
}
});
}
/**
* Called when the screen rotates. If this isn't handled, data already generated is no longer available
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();
if (list != null) {
outState.putParcelableArrayList(DEVICE_LIST, list);
int selectedIndex = adapter.selectedIndex;
outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case BT_ENABLE_REQUEST:
if (resultCode == RESULT_OK) {
msg("Bluetooth Enabled successfully");
new SearchDevices().execute();
} else {
msg("Bluetooth couldn't be enabled");
}
break;
case SETTINGS: //If the settings have been updated
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uuid = prefs.getString("prefUuid", "Null");
mDeviceUUID = UUID.fromString(uuid);
Log.d(TAG, "UUID: " + uuid);
String bufSize = prefs.getString("prefTextBuffer", "Null");
mBufferSize = Integer.parseInt(bufSize);
String orientation = prefs.getString("prefOrientation", "Null");
Log.d(TAG, "Orientation: " + orientation);
if (orientation.equals("Landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("Portrait")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("Auto")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Quick way to call the Toast
* #param str
*/
private void msg(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
/**
* Initialize the List adapter
* #param objects
*/
private void initList(List<BluetoothDevice> objects) {
final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
mLstDevices.setAdapter(adapter);
mLstDevices.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedIndex(position);
mBtnConnect.setEnabled(true);
}
});
}
/**
* Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
* will show up with this. I didn't see any need to re-build the wheel over here
* #author ryder
*
*/
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
#Override
protected void onPostExecute(List<BluetoothDevice> listDevices) {
super.onPostExecute(listDevices);
if (listDevices.size() > 0) {
MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
adapter.replaceItems(listDevices);
} else {
msg("No paired devices found, please pair your serial BT device and try again");
}
}
}
/**
* Custom adapter to show the current devices in the list. This is a bit of an overkill for this
* project, but I figured it would be good learning
* Most of the code is lifted from somewhere but I can't find the link anymore
* #author ryder
*
*/
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
private int selectedIndex;
private Context context;
private int selectedColor = Color.parseColor("#abcdef");
private List<BluetoothDevice> myList;
public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
super(ctx, resource, textViewResourceId, objects);
context = ctx;
myList = objects;
selectedIndex = -1;
}
public void setSelectedIndex(int position) {
selectedIndex = position;
notifyDataSetChanged();
}
public BluetoothDevice getSelectedItem() {
return myList.get(selectedIndex);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public BluetoothDevice getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView tv;
}
public void replaceItems(List<BluetoothDevice> list) {
myList = list;
notifyDataSetChanged();
}
public List<BluetoothDevice> getEntireList() {
return myList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.tv = (TextView) vi.findViewById(R.id.lstContent);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (selectedIndex != -1 && position == selectedIndex) {
holder.tv.setBackgroundColor(selectedColor);
} else {
holder.tv.setBackgroundColor(Color.WHITE);
}
BluetoothDevice device = myList.get(position);
holder.tv.setText(device.getName() + "\n " + device.getAddress());
return vi;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Homescreen.this, PreferencesActivity.class);
startActivityForResult(intent, SETTINGS);
break;
}
return super.onOptionsItemSelected(item);
}
}
This is my second class BluetoothService Class
public class BluetoothService extends Service {
public static BluetoothService service;
private boolean mConnectSuccessful = true;
private static boolean isRunning = false;
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
//private UUID mDeviceUUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private boolean mIsBluetoothConnected = false;
//private BluetoothDevice mDevice=Homescreen.home.device;
private BluetoothDevice mDevice;
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
// Intent intt = getIntent();
// Bundle b = intt.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
// super.onStart(intent, startId);
}
#Override
public void onCreate() {
service=this;
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
// TODO Auto-generated method stub
// Intent intent = getIntent();
// Bundle b = intent.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.i("mDeviceUUID", ""+mDeviceUUID);
Log.d("mDevice",""+mDevice );
new ConnectBT().execute();
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
public boolean isRunning() {
return isRunning;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
super.onDestroy();
}
class ConnectBT extends AsyncTask<Void, Void, Void> {
//ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// http://stackoverflow.com/a/11130220/1287554
// progressDialog = ProgressDialog.show(BluetoothService.this, "Hold on", "Connecting");
Log.d("check check check", "check1");
}
#Override
protected Void doInBackground(Void... devices) {
Log.d("check check check", "check2");
try {
Log.e("check check check", "check3");
if (mBTSocket == null || !mIsBluetoothConnected) {
Log.e("UUID", ""+mDeviceUUID);
Log.e("mDevice", ""+mDevice);
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
Log.d("check check check", "check4");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
Log.d("check check check", "check5");
// Toast.makeText(BluetoothService.this, "background service start", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(BluetoothService.this, "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
Log.e("Device Status in service", "Disconnected");
} else {
Toast.makeText(BluetoothService.this, "Connected to device", Toast.LENGTH_SHORT).show();
Log.e("Device Status in service", "Device Connected");
mIsBluetoothConnected = true;
// Kick off input reader
}
//progressDialog.dismiss();
}
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device connected","BT Connected");
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device disconnected","BT Disconnected");
}
//else if...
}
};
}
Android's AsyncTask class will help you. Do the bluetooth discovery task in the doInBackground() method of AsyncTask.You can Toast a message a after the task in the onPostExecute() method. Here is sample code snippet to demonstrate the use of AsyncTask

Categories

Resources