BluetoothSocket.isConnected issue - android

I have created an Android Application in that if my Android has a Bluetooth connection to my computer and I power down my computer, isConnected still returns true. Anyone know if this can be fixed?
I'm not sure if there's a Bluetooth heartbeat or not.

Try this.
IntentFilter connectivityFilter = new IntentFilter();
connectivityFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
connectivityFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(bluetoothModeCheckingReceiver, connectivityFilter);
private final BroadcastReceiver bluetoothModeCheckingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// to do
} else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
// to do
}
}
};

Related

Getting notified about change in state of WiFi on android device?

I am aiming to build a android app which record everything going on with devices WiFi adapter. For example WiFi being turned on/off, device getting connected/moving out of range of a WiFi router, etc.
My app should be able to record these events as soon as the device is turned on. Clearing the app from RECENTS should not affect the ability of the app to record these events.
I have gone through BroadcastReceiver. It gets tied to the life cycle of the app and hence will not record the events once app gets cleared from RECENTS.
public class MainActivity extends Activity {
BroadcastReceiver mybroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mybroadcastReceiver = new WifiBroadcastReceiver(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
registerReceiver(mybroadcastReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mybroadcastReceiver);
}
}
public class WifiBroadcastReceiver extends BroadcastReceiver {
final String TAG = "WifiBroadcastReceiver";
final String desiredMacAddress = "02:17:1c:96:42:fa";
Activity activity;
WifiBroadcastReceiver(Activity activity) {
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(action)) {
SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
if (SupplicantState.isValidState(state) && state == SupplicantState.COMPLETED)
checkConnectedToDesiredWifi();
}
}
/** Detect you are connected to a specific network. */
private void checkConnectedToDesiredWifi() {
WifiManager myWifiManager = (WifiManager)activity.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = myWifiManager.getConnectionInfo();
if (wifiInfo != null) {
// get current router MAC address
String bssid = wifiInfo.getBSSID();
if (desiredMacAddress.equals(bssid))
Log.d(TAG, "Connected to " + bssid + " i.e., desiredMacAddress");
else
Log.d(TAG, "Connected to " + bssid + " not " + desiredMacAddress);
}
}
}
One solution could be to run the BroadcastReceiver from a Service that doesn't depend on the lifecycle of any Activity.
1) Declare the network state permission usage in the manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1) Create a Service class
public class WifiService extends Service {
private BroadcastReceiver mReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
// When creating the service, register a broadcast receiver
// to listen for network state changes
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new WifiReceiver();
registerReceiver(mReceiver, filter);
return null;
}
#Override
public boolean onUnbind(Intent intent) {
// Unregister the receiver when unbinding the service
unregisterReceiver(mReceiver);
mReceiver = null;
return super.onUnbind(intent);
}
}
2) Create a BroadcastReceiver
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null &&
networkInfo.isConnectedOrConnecting();
if (isConnected) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
// Connected via wifi
checkConnectedToDesiredWifi();
break;
case ConnectivityManager.TYPE_ETHERNET:
// Connected via ethernet
break;
case ConnectivityManager.TYPE_MOBILE:
// Connected via mobile data
break;
}
}
}
private void checkConnectedToDesiredWifi() {
// ...
}
}
3) Declare the service in the manifest
<service android:name=".receivers.WifiService"
android:stopWithTask="false"
android:enabled="true"/>

in Android, how do we periodically scan for bluetooth devices?

The bluetooth scan should stop as soon as it finds a device of choice, and then after stopping it should start again, when i do the following, i get error saying the app has stopped. i want to scan for 3 times, and store their radiuses.
private BluetoothAdapter mBtAdapter;
mBtAdapter.startDiscovery();
//this string stores the MAC Address of the required device
string name = "12:34:D3:s3:we";
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
if(device.getAddress.equals(name)){
mBtAdapter.cancelDiscovery();
}
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
{
mBtAdapter.startDiscovery();
}
}
}

Detect when USB device detached from Android device

I am using a usb POS printer with my application. I have successfully written the code to connect, request permission and print data. However, I'm unsure how do notify the user when the printer is disconnected, if it is then the device falls back to the network printer.
So this is my BroadcastReceiver for requesting permission:
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
mDevice = device;
if(mConnection == null){
Log.i(m_Tag, "Connection is null");
}
Log.i(m_Tag, "Connected successfully");
}else{
Log.i(m_Tag, "Device is null");
}
}
else {
}
}
}
}
};
I have trawled through the forums here and suggested answers and I've checked out this http://developer.android.com/guide/topics/connectivity/usb/host.html I can't find a solid way to do it without including a device filter xml file. I can't do this because I'm unsure as to what model of printer will be used by the end user.
My brain is fried from this, if someone could please point out how to do this, I'd greatly appreciate it.
Quite late, but for future readers here is how I do it.
In onStart() I register a broadcast receiver for the ACTION_USB_DEVICE_DETACHED action.
#Override
protected void onStart() {
Log.d(TAG, "onStart()");
super.onStart();
// Catch a USB detach broadcast intent.
detachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
jobsDone();
}
}
};
// Set the intent filter for the broadcast receiver, and register.
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(detachReceiver, filter);
}
In my jobsDone() I just finish the Activity which is basically the same as pressing "back".
private void jobsDone() {
Log.d(TAG, "jobsDone()");
this.finish();
}
Since in my case only one USB device can be attached at one single time I do not have to bother with device_filter.xml for the detach.
Also remember to unregister the receiver.
#Override
protected void onStop() {
Log.d(TAG, "onStop()");
super.onStop();
// Unregister the BroadcastReceiver
unregisterReceiver(detachReceiver);
}

Android Broadcast receiver for RJ45 ethernet cable

I am creating a sample code, for detecting whether the RJ45 cable is connected or not. I have written a broadcast receiver for the detecting.
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
Log.i("Calling Connectivity action in broadcast receiver ", "");
updateConnectivity(intent);
}
}
private void updateConnectivity(Intent intent) {
NetworkInfo info = (NetworkInfo)(intent.getParcelableExtra(
ConnectivityManager.EXTRA_NETWORK_INFO));
if (info != null && info.getType() == ConnectivityManager.TYPE_ETHERNET) {
mEthernetConnected = info.isConnected();
}
if(mEthernetConnected)
Log.i("Ethernet connected status is ", "" +mEthernetConnected);
else
Log.i("Ethernet connected status is ", "" +mEthernetConnected);}
I am registering this an activity class
intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mBroadcastReceiver = new EthernetReceiver(this);
this.registerReceiver(mBroadcastReceiver, intentFilter);
Here in this it is returning only false in logs. can any one has idea how to fix this issue. Thanks in advance.

Android Bluetooth Discovery in a sequential method?

I am new to Android programming. I want to make a library (a JAR file) that contains the Bluetooth discovery functionality.
Since it is a library, the method inside should be a sequential method (start the Bluetooth discovery, wait for an amount of time, and return the result).
I made a code below, but it does not work. In the LogCat, I could see the intents, but the BroadcastReceiver could not catch the intents.
Is there something wrong with the code?.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mSendButton = (Button) findViewById(R.id.button1);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
}
});
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("device_name", device.getName());
Log.e("device_add", device.getAddress());
numberOfDevice++;
Found_Device = true;
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if(numberOfDevice == 0){
Log.e("DISCOVERY", "No Device found");
}
Log.e("DISCOVERY", "Number of device :" + numberOfDevice);
Discovery_Finish = true;
}
}
};
public void doDiscovery(){
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
Discovery_Finish = false;
Found_Device = false;
long counter = 0;
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
while((Found_Device == false) || (Discovery_Finish == false)){
counter++;
if (counter >= 1000000){
break;
}
}
// Add a code to check the number of device
unregisterReceiver(mReceiver);
mBluetoothAdapter.cancelDiscovery();
}
Is there any way to check the intent without using BroadcastReceiver?
Thank you for your help.
I think you are missing to start the discovering the other devices.
You are overwriting your IntentFilter when you do this:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
You should do it like this:
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);

Categories

Resources