There is a device with embedded laser barcode scanner and hardware SCAN button on Android 4.4.2. Is there any method to hook qr scan event with java interface?
Device is Sunlux xl-8681d but it detects as x301 in adb device list.
I have worked with similar device. When you click on some area where you can edit text, and scan a bar code, will it print it on the field? If yes, then you can use the following snippet inside your Activity:
Override dispatchKeyEvent method. Small sample:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getCharacters() != null && !event.getCharacters().isEmpty())
//Add more code...
return super.dispatchKeyEvent(event);
}
You can do it even without EditText. You need to subscribe for broadcast intent like this:
const val QR_ACTION: String = "android.intent.ACTION_DECODE_DATA"
const val QR_EXTRA: String = "barcode_string"
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
try {
Timber.d("Get intent ${intent.action}")
if (QR_ACTION == intent.action) {
if (intent.hasExtra(QR_EXTRA)) {
val code = intent.getStringExtra(QR_EXTRA)
Timber.d("New QR code $code")
// now you have qr code here
}
} }
} catch (t: Throwable) {
// handle errors
}
}
}
Please check QR_ACTION and QR_EXTRA first in to your scanner settings it can be different for different brands.
Related
i have an application, and my application can connect to a bluetooth device.
After that, i want to send message (Int) to my Blutooth Low Energy device.
I have this code, but i can't figure it out what is the problem.
If you want i have : Characteristic UUID, Service UUID.
Really, i need your help...
I've edited the question :
My code :
val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
lateinit var bluetoothAdapter: BluetoothAdapter
val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
settingViewModel.bluetooth(bluetoothAdapter = bluetoothAdapter)
val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action
if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
val state = intent.getIntExtra(
BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR
)
when (state) {
BluetoothAdapter.STATE_OFF -> {
settingViewModel.setIsConnected(false)
//settingViewModel.stopScan()
settingViewModel.setListDevices(null)
}
BluetoothAdapter.STATE_ON -> {
settingViewModel.setIsConnected(true)
//scan()
settingViewModel.setListDevices(bluetoothAdapter.bondedDevices)
context!!.unregisterReceiver(this)
}
}
}
}
}
context.registerReceiver(mReceiver, filter)
val SERVICE_UUID = "00000000-0001-11e1-9ab4-0002a5d5c51c"
val ConfigCharacteristic = descriptorOf(
service = SERVICE_UUID,
characteristic = "00E00000-0001-11e1-ac36-0002a5d5c51b",
descriptor = "00000000-0000-0000-0000-000000000000",
)
Button(
onClick = {
if (settingViewModel.isConnected.value == true) {
coroutine.launch(Dispatchers.IO) {
try {
settingViewModel.peripheral.write(ConfigCharacteristic, byteArrayOf(1))
} catch (e: Exception) {
Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
}
}
}
// try {
// val Service =
// settingViewModel.deviceSocket.value.get .getService(UUID.fromString("0000ffe0-0000-1000-8000-00805f9b34fb"))
// val charac: BluetoothGattCharacteristic =
// Service.getCharacteristic(UUID.fromString("00E00000-0001-11e1-ac36-0002a5d5c51b"))
// settingViewModel.deviceSocket.value!!.outputStream.write("1".toByteArray())
// } catch (e: Exception) {
// Toast.makeText(context, e.message.toString(), Toast.LENGTH_LONG).show()
// }
}
) {
Text(text = "HelloWorld")
}
I Already have the mac adress, the caracteristic and the service UUID of the device i want to connect to.
Again, i really need your help
First of all:
When developing an app for a BLE device it is best to first use a generic BLE scanner app to test the connection and to find out which commands need to be sent. If you confirm that the BLE device works as expected you can continue with your own custom app. I would recommend nRF Connect for this task.
Regarding your problem:
There are still many things missing from your sourcecode. You said you can connect to the device but have problems sending a message. Your code does not contain anything related to a BLE connection so I can only assume that you connected to the device using the Bluetooth settings of your phone. This would be correct for Bluetooth Classic but BLE requires you to connect through your own custom app.
The Ultimate Guide to Android Bluetooth Low Energy explains all steps necessary for a successful BLE connection. These steps are:
Setting the correct permissions
Scan for nearby BLE devices
Connect to a BLE device of your choosing
Scan for Services
Read and Write a characteristic of your choosing
All these steps are explained in the Guide using Kotlin as programming language.
I am new to Android NFC and developing NFC application in android. My idea is Device A need to send a plain text to Device B. Is it possible in Android NFC?
I just tried with Tag Dispatcher (enableForegroundDispatch , disableForegroundDispatch) on both Reader and Writer.
My Reader side code is :
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, techList)
override fun onNewIntent(intent: Intent?) {
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.also { rawMessages ->
val messages: List<NdefMessage> = rawMessages.map { it as NdefMessage }
for (message in messages) {
for (record in message.records) {
println(" ${record.toString()}")
}
}
}
}
My Writer side code is:
nfcAdapter.enableForegroundDispatch(
this, pendingIntent, intentFilters, techList)
override fun onNewIntent(intent: Intent?) {
if (action.equals(NfcAdapter.EXTRA_TAG)) {
val tagFromIntent = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)
) {
println("testing=============== tag discovered ")
writeNdefMessage(tagFromIntent!!, "This is my first app")
}
}}
private fun writeNdefMessage(tag: Tag, message: String) {
val record: NdefRecord = newTextRecord(message, Locale.ENGLISH, true)!!
val ndefMessage = NdefMessage(arrayOf(record))
try {
if (isExist(tag.techList, NdefFormatable::class.java.name)) {
val ndefFormatable = NdefFormatable.get(tag)
try {
if (!ndefFormatable.isConnected) {
ndefFormatable.connect()
}
ndefFormatable.format(ndefMessage)
} finally {
ndefFormatable.close()
}
} else if (isExist(tag.techList, Ndef::class.java.name)) {
val ndef = Ndef.get(tag)
try {
if (!ndef.isConnected) {
ndef.connect()
}
if (ndef.isWritable) {
ndef.writeNdefMessage(ndefMessage)
}
} finally {
ndef.close()
}
}
} catch (e: FormatException) {
println("Format failed exception")
} catch (e: IOException) {
println("")
}
}
Application is launched when I scan the Tag (via AndroidManifest.xml details). But I am not able to send plain text via NFC. I don't know what I did wrong. I don't know whether the approach is right or wrong. Please help me to proceed this.
Thanks in advance.
So in Android peer to peer NFC (Device to Device) also called Android Beam has been deprecated as of API 29
See https://developer.android.com/reference/android/nfc/NfcAdapter#setNdefPushMessage(android.nfc.NdefMessage,%20android.app.Activity,%20android.app.Activity...)
You are using the wrong methods to use Android Beam in older Android Versions.
See https://developer.android.com/guide/topics/connectivity/nfc/nfc#p2p for more details of actually how to use it. (You are using methods for writing to a NFC card not another Device)
Note Peer to Peer via NFC is Android only, iOS does not support it and it is depreciated in favour of Bluetooth/Wifi Direct
Note that it is still possible to have one Android Device use Host Card Emulation to Emulate a Type 4 NFC card with an NDEF messages on it but this is quite complicated to achieve.
Update:
Link to Host Card Emulation https://developer.android.com/guide/topics/connectivity/nfc/hce and Type 4 card spec http://apps4android.org/nfc-specifications/NFCForum-TS-Type-4-Tag_2.0.pdf
I have a thirdparty Android control that can't be used in Flutter directly. I put it in an Android activity. Then, using information from https://flutter.io/docs/development/platform-integration/platform-channels#step-3b-add-an-android-platform-specific-implementation-using-kotlin, I can successfully launch that activity and perform some actions there. The only part that doesn't work is sending results back from the activity.
Flutter code:
void showDialog() async
{
try {
final Map<String, List<double>> result = await platform.invokeMethod('show_dialog',
<String, String>{
'address': widget.user.address
});
widget.user.address = result.keys.toList()[0];
} on PlatformException catch (e) {
print('Failed to pick address: ${e.message}.');
}
}
Android code:
class MainActivity: FlutterActivity() {
private val CHANNEL = "dialog"
private lateinit var _result: MethodChannel.Result
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "show_dialog") {
_result = result
val intent = Intent(this#MainActivity, DialogActivity::class.java)
intent.putExtra("address", call.argument<String>("address"))
startActivityForResult(intent, 9689)
}
else result.notImplemented()
}
}
override fun onActivityResult(requestCode: Int, result: Int, intent: Intent?) {
if(requestCode != 9689)
return super.onActivityResult(requestCode, result, intent)
if (result == Activity.RESULT_OK) {
_result.success(mapOf(intent!!.getStringExtra("address") to
listOf(intent.getDoubleExtra("latitude", 0.0),
intent.getDoubleExtra("longitude", 0.0))))
}
else
_result.success(null)
}
}
What's the problem? Breakpoint on the line widget.user.address = result.keys.toList()[0]; is never reached, suggesting the result is never sent back.
Turns out the code was almost correct. The Android side didn't need any changes, but on the Flutter side I had to make this change:
turn
final Map<String, List<double>> result = await platform.invokeMethod(
into
final result = await platform.invokeMethod(
i. e. simply remove explicit type from the variable, because the return value of platform.invokeMethod was some kind of an internal hash map (in particular, it's name started with an underscore) rather than that of Map as specified. Flutter didn't show any errors in the console output, because for some reason it only captures Android log with debugger attached to the Android part of the application, and once I figured how to debug Android code in Android Studio, I immediately found the reason.
I've got a bit of my app that is dedicated to sharing files between devices over bluetooth using a quick, ad-hoc protocol that I put together. Currently, in the containing Activity I begin discovery, and add any device that I find into a RecyclerView. Here is the code for the BroadcastReceiver that is handling that:
private val scanReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == BluetoothDevice.ACTION_FOUND) {
val dev = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
Log.d(TAG, "Got device ${dev.name} with address ${dev.address}")
if (dev.name != null) {
Log.d(TAG, "Found nonnull device name, adding")
if (!viewAdapter.dataset.any { it.name == dev.name }) {
viewAdapter.dataset.add(dev)
viewAdapter.notifyDataSetChanged()
}
}
}
}
}
I wanted to modify this in such a way that it would only add devices who were broadcasting with the service UUID that I set up in the server portion of the app. After doing some research I came to this method that I could use to get the UUIDs of the services on the device. I integrated that into my BroadcastReceiver as such
private val scanReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
BluetoothDevice.ACTION_FOUND -> {
val dev = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
Log.d(TAG, "Got device ${dev.name} with address ${dev.address}")
if (dev.name != null) {
dev.fetchUuidsWithSdp()
}
}
//TODO: Untested code
BluetoothDevice.ACTION_UUID -> {
val id = intent.getParcelableExtra<ParcelUuid>(BluetoothDevice.EXTRA_UUID)
if (id.uuid == ShareServerSocket.SERVICE_UUID) {
val dev = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
if (!viewAdapter.dataset.any { it.name == dev.name }) {
viewAdapter.dataset.add(dev)
viewAdapter.notifyDataSetChanged()
}
}
}
}
}
}
(With requisite modifications to the IntentFilter I'm registering it with).
The code in the new branch gets called, I validated that with some debugging output. However, the ParcelUuid[] that I am given never contains the UUID of my service, and the device therefore never gets added. If I keep the entire setup the same on the device acting as a server, and bypass the new check on the client, I am able to connect and interact just fine. I'm unsure as to why my service wouldn't be being shown at this point.
P.S. I did also check the SDP cache, my service UUID is not there, either.
It turns out I was running into the same issue as described in Strange UUID reversal from fetchUuidsWithSdp. Stealing that workaround made it work.
I know It's impossible to enable the Accessibility service for apps programmatically, so I'd like to direct users to this screen:
System settings --> Accessibility --> app name --> enable/disable screen.
Is that possible ?
You can get them to the Accessibility screen on most devices using ACTION_ACCESSIBILITY_SETTINGS. However:
that may not work on all devices, so you will want to just send them to Settings as a fallback, if you get an ActivityNotFoundException
there is no way to get them straight to any given app, let alone the enable/disable screen
You can at least make it reach the app, making the app item blink. It should work for most devices, or at least those that are like of Pixel devices:
fun <T : AccessibilityService> getRequestAccessibilityPermissionIntents(context: Context, accessibilityService: Class<T>): Array<Intent> {
var intent = Intent("com.samsung.accessibility.installed_service")
if (intent.resolveActivity(context.packageManager) == null) {
intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
}
val extraFragmentArgKey = ":settings:fragment_args_key"
val extraShowFragmentArguments = ":settings:show_fragment_args"
val bundle = Bundle()
val showArgs = "${context.packageName}/${accessibilityService.canonicalName!!}"
bundle.putString(extraFragmentArgKey, showArgs)
intent.putExtra(extraFragmentArgKey, showArgs)
intent.putExtra(extraShowFragmentArguments, bundle)
return arrayOf(intent, Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY))
}
Usage:
private fun requestAccessibilityPermission() {
getRequestAccessibilityPermissionIntents(this, MyAccessibilityService::class.java).forEach { intent ->
try {
startActivity(intent)
return
} catch (e: Exception) {
}
}
//TODO do something here in case it failed
}