Detect when USB device detached from Android device - android

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);
}

Related

Handle Connection state at boot of device in android

I am making dynamic Register Receiver for Listening connection of internet in android 7.1 and it is starting correctly When internet connection is changed, I handled in OnReceive() method in NetworkChngeReceiver but When I boot device I can't handle connection of internet, my application is started at startup When device is booted, how can I listen connection of internet at boot time of device?
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate((Bundle savedInstanceState)){
mNetworkReceiver = new NetworkChangeReceiver(context, this);
}
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public NetworkChangeReceiver(Context context,Activity a){
try {
c = context;
activity = a;
wifiScanReceiver = new WifiScanReceiver(context);
wifiManager = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onReceive(Context context, Intent intent)
{}
}
When device booting there won't be happening any change of network connection status so won't trigger NetworkChangeReceiver. We can get a connection status by ConnectivityManager.

BluetoothSocket.isConnected issue

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
}
}
};

Discovering Bluetooth devices on Android

I've searched and tried everything I could, but I just can't get this to work. From all the examples I've seen, I seem to be doing the right thing, but maybe I'm missing something.
I'm trying to discover Bluetooth devices on Android and have been following the guide on the Android Developer page: http://developer.android.com/guide/topics/connectivity/bluetooth.html
I can enable BT when the app starts and get the name and address of my device. However, I can't see the names of other nearby devices (supposed to show up as a toast). The intriguing part is, when I enable BT before starting the app, it actually does what I want and shows the nearby devices' name.
Here's the code:
public class MainActivity extends AppCompatActivity {
TextView mTextView;
BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
final String status;
// Check BT support
if (mBluetoothAdapter == null){
// Device does not support BT
status = "Your device does not support Bluetooth";
}
else {
String myAddress = mBluetoothAdapter.getAddress();
String myName = mBluetoothAdapter.getName();
status = myName + ": " + myAddress;
}
mTextView = (TextView)findViewById(R.id.textView);
// If BT is enabled before app start, discover devices
// This is where things work, for some reason
if (mBluetoothAdapter.isEnabled()){
mTextView.setText(status);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
// If BT is not enabled, enable it and look for devices
else{
mTextView.setText(status);
mBluetoothAdapter.enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver, filter);
getBTdevices();
}
}
protected void getBTdevices(){
// Stop discovery and start
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText("Start");
String action = intent.getAction();
// If device is found
if (BluetoothDevice.ACTION_FOUND.equals(action)){
// Get BT device from intent
textView.setText("Device found");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(context, "Device found: "+ device.getName(), Toast.LENGTH_LONG).show();
System.out.println("Discovered!");
}
}
};
protected void onDestroy(){
super.onDestroy();
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(mBroadcastReceiver);
}
}
Some help would really be appreciated, I don't know what else I can do.
EDIT: Forgot to mention, I have set both the BLUETOOTH and BLUETOOTH_ADMIN permissions in the manifest.

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();
}
}
}

Why Android devices won't read NFC tags after a long sleep?

I'm sorry for my bad English.
I develop an Android app using NFC. I added a method that stops unsecured keyguards temporarily to the app for the purpose of quickly uses NFC tags.
However, I thought stopping keyguards causes battery drains when sleeping, so I added a method that recovers keyguards when devices are sleeping.
As a result, I wrote codes shown below.
public class MainActivity extends Activity {
private NfcAdapter mAdapter;
private PowerManager mPowerManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// regist screen on / off actions receiver
IntentFilter scFilter = new IntentFilter();
scFilter.addAction(Intent.ACTION_SCREEN_ON);
scFilter.addAction(Intent.ACTION_SCREEN_OFF);
scFilter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mScreenReceiver, scFilter);
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
String action = intent.getAction();
if (action != null && (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)
|| action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)
|| action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))) {
// manage NFC Tags here
Log.d("MainActivity", "NFC Tags detected");
Toast.makeText(getApplicationContext(), "NFC Tags detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onResume() {
super.onResume();
// enableForegroundDispatch
if (mAdapter == null) {
mAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());
}
if (mAdapter != null) {
Intent nfcIntent = new Intent(this, getClass());
nfcIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, nfcIntent, 0);
mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
} else {
Log.d("MainActivity", "failed getDefaultAdapter()");
}
}
#Override
public void onPause() {
if (mPowerManager != null) {
if (!mPowerManager.isScreenOn()) {
// clearWindowFlags only when device is sleeping
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
}
// disableForegroundDispatch
if (mAdapter != null) {
mAdapter.disableForegroundDispatch(this);
mAdapter = null;
}
super.onPause();
}
#Override
public void onDestroy() {
try {
// unregist screen on / off actions receiver
unregisterReceiver(mScreenReceiver);
} catch (IllegalArgumentException e) {
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == null) {
return;
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
}
}
};
}
But, this code didn't perform as intended on my device.
I use Nexus 7 (1st, OS 4.3, Slide lock enabled).
First, when I launched the app and put my device into sleep, keyguards didn't recover with a probability of 30%. It sounds read sound effects with NFC tags even when sleeping.
Second, my device rarely won't read NFC tags after about an hour sleep with using the app. It will not even sound anything with NFC tags. But the condition goes off after sleep again or terminating the app.
Who does know causes of the bugs?

Categories

Resources