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.
Related
I want to implement passkey for connect device or establish the connection with BLE device. I have 6 byte passkey, So how we will create bond or pairing and send passkey to the BLE device using RxAndroid library.
Can any one give me reference or document link or demo link for implementation of Passkey or create bond or pairing while establish connection.
Thanks in advance!!
First you need to find the nearby devices.
public void registerDeviceForAnyNEwDeviceFound() {
// Register for broadcasts when a device is discovered.
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mSearchReceiver, filter);
Log.e("STATUS", "" +
mBluetoothAdapter.isDiscovering());
isSearchReceiverRegistered = true;
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("SEARCH STARTED", "TRUE");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Device mDevice = new Device();
mDevice.setDeviceName(deviceName);
mDevice.setDeviceAddress(deviceHardwareAddress);
mDevice.setmBluetoothDevice(device);
Log.e("Discovered DEVICE", deviceName);
Log.e("BOND STATE", "" + device.getBondState());
nearbyDeviceList.add(mDevice);
mNearbyDeviceRecAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("EXCEPTION", e.getLocalizedMessage());
}
}
}
};
Then you need to register another BroadCastReceiver, this receiver will listen to the bond changes with the device with whom you are going to pair with.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairingReceiver, filter);
private final BroadcastReceiver mPairingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDED." + mDevice.getName());
mBluetoothAdapter.cancelDiscovery();
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDING." + mDevice.getName());
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
Log.e(TAG, "BroadcastReceiver: BOND_NONE." + mDevice.getName());
}
}
}
};
Finally when you want to pair with the device call:
mNearbyDeviceRecAdapter.getItemAtPosition(position).getmBluetoothDevice().createBond();
Once you call this statement, this will initiate pairing with the device.
Hope! this helps.
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
}
}
};
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"/>
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);
}
I want to check Internet connection throughout the run time of my Android application. I tried using services but seems like it is not the best option. Is there any possible way for me to implement a broadcast receiver with in a service? Or do I have to give up the service and use broadcast receivers alone?
I will show you how to create SMS receiver in a service:
public class MyService extends Service {
#Override
public void onCreate() {
BwlLog.begin(TAG);
super.onCreate();
SMSreceiver mSmsReceiver = new SMSreceiver();
IntentFilter filter = new IntentFilter();
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
filter.addAction(SMS_RECEIVE_ACTION); // SMS
filter.addAction(WAP_PUSH_RECEIVED_ACTION); // MMS
this.registerReceiver(mSmsReceiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
/**
* This class used to monitor SMS
*/
class SMSreceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (TextUtils.equals(intent.getAction(), SMS_RECEIVE_ACTION)) {
//handle sms receive
}
}
}
It wouldn't be wise to check for the connectivity every second. Alternatively you can listen to the action (ConnectivityManager.CONNECTIVITY_ACTION) and identify if you are connected to an active network or not.
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Additionally you can check the network Type that is currently active(Type_WIFI, Type_MOBILE)
This way, you don't need a service that keeps checking the connectivity every second.
You need not to use Service or BroadCastReceiver for this purpose. Just check Connection status everyTime you need to ping the server.
you can write a method which checks this and returns a boolean(true/false) according to connection status.
Below method does the same.
public static boolean isNetworkAvailable(Context mContext) {
try {
final ConnectivityManager conn_manager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo network_info = conn_manager
.getActiveNetworkInfo();
if (network_info != null && network_info.isConnected()) {
if (network_info.getType() == ConnectivityManager.TYPE_WIFI)
return true;
else if (network_info.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
} catch (Exception e) {
// TODO: handle exception
}
return false;
}