How to check if device has infra-red in Android? - android

How do I know if device has Infra-red hardware in android pragmatically?
I want to have some things to be done based on this. I tried using something like below, but no luck.
this.getPackageManager().hasSystemFeature( .. various constants ..)

Use ConsumerIrManager.hasIrEmitter()

Try Following Code
Kotlin:
val irManager: ConsumerIrManager = getSystemService(CONSUMER_IR_SERVICE) as ConsumerIrManager
// Check whether IrEmitter is available on the device.
if (irManager.hasIrEmitter()) {
Log.i("IR_Testing", "found IR Emitter")
}else{
Log.i("IR_Testing", "Cannot found IR Emitter on the device")
}
Java:
private ConsumerIrManager irManager ;
irManager = (ConsumerIrManager) getSystemService(CONSUMER_IR_SERVICE);
if (irManager.hasIrEmitter()) {
Log.i("IR_Testing", "found IR Emitter");
} else {
Log.i("IR_Testing", "Cannot found IR Emitter on the device");
}

Related

how to recognize USB and mounted state in Android Box

i am developing an android app, and this app need an information about ExternalStoarage State(this mean, USB, Not a SdCard).
so i thought this code could get a USB Mounted State
Environment.getExternalStorageState()
But it always return about SdCard. I don't know how to access to USB Storage in Android Device. but almost Android device is a Phone so i cannot find about my case
Here is a code block from the official Android guide:
val manager = getSystemService(Context.USB_SERVICE) as UsbManager
..
val deviceList: HashMap<String, UsbDevice> = manager.deviceList
deviceList.values.forEach { device ->
//your code
}
private lateinit var bytes: ByteArray
private val TIMEOUT = 0
private val forceClaim = true
...
device?.getInterface(0)?.also { intf ->
intf.getEndpoint(0)?.also { endpoint ->
usbManager.openDevice(device)?.apply {
claimInterface(intf, forceClaim)
bulkTransfer(endpoint, bytes, bytes.size, TIMEOUT) //do in another thread
}
}
}
It will help you to find your USB connected device and communicate with it. Please check the link above for more information.

How to play audio through earpiece in android 12?

I am developing a voice call app for android using PeerJS and WebView. And I want the audio to play through the earpiece. Here is my code,
private fun initAudio(){
am = getSystemService(AUDIO_SERVICE) as AudioManager
volumeControlStream = AudioManager.STREAM_VOICE_CALL
am.mode = AudioManager.MODE_IN_COMMUNICATION
am.isSpeakerphoneOn = false//<= not working in android 12
}
private fun toggleSpeakerMode(){
am.isSpeakerphoneOn = !am.isSpeakerphoneOn // <= final value is always true in android 12
}
The above code works fine on older versions of android, but not in android 12 (emulator).
am.isSpeakerphoneOn is always true in android 12. Am I doing something wrong here? Or is it a bug in the emulator?
there is a new API call in Android 12/S/API 31, setCommunicationDevice(AudioDeviceInfo). for switching between speaker an built-in earpiece now we can use:
ArrayList<Integer> targetTypes = new ArrayList<>();
if (earpieceMode) {
targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_EARPIECE);
} else { // play out loud
targetTypes.add(AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
}
// more targetTypes may be added in some cases
// set up will pick and first available, so order matters
List<AudioDeviceInfo> devices = audioManager.getAvailableCommunicationDevices();
outer:
for (Integer targetType : targetTypes) {
for (AudioDeviceInfo device : devices) {
if (device.getType() == targetType) {
boolean result = audioManager.setCommunicationDevice(device);
Log.i("AUDIO_MANAGER", "setCommunicationDevice type:" + targetType + " result:" + result);
if (result) break outer;
}
}
}
mode change isn't needed (but for voip calls is strongly suggested) and my streams are AudioManager.STREAM_VOICE_CALL type (where applicable)
By default webrtc uses earpiece for voice playing.
However,alternatively You can call the setSpeakerphoneOn(false) that is defined in the AudioManager.java class.
Just pass false in this function parameter and it will disable the speaker phone in the call and earpiece will be used.
I have also tested it on the android 12 phones and it is working fine.
If issue still persist then you have some bug in your emulator.

Unity XR.Settings.LoadDeviceByName() not loading device

I have tried to use XRSettings.LoadDeviceByName() but it never work. I have already check if the parameter device name is same as the current device name but nothing changes. Also, I have added the None in the sdk list
The XRSettings.loadedDeviceName is cardboard when initiating.
IEnumerator testThis() {
if (string.Compare(XRSettings.loadedDeviceName, "", true) != 0) {
XRSettings.LoadDeviceByName("none");
some_text.text = XRSettings.loadedDeviceName;
yield return new WaitForSeconds(1);
XRSettings.enabled = true;
some_text.text = "Device name " + XRSettings.loadedDeviceName;
}
}
IEnumerator temp() {
some_text.text = "Device name " + XRSettings.loadedDeviceName;
yield return new WaitForSeconds(10);
StartCoroutine(testThis());
}
No matter how I detect, the device name is still cardboard.
https://docs.unity3d.com/ScriptReference/XR.XRSettings.LoadDeviceByName.html
What I have done:
Make None as one of the Virtual Reality SDKs
Use XR-Plugin Management
2.1 Disable Virtual Reality Supported
2.2 Convert camera to XR-Rig
2.3 Use the code about turning VR off in XR-Plugin Management
2.4 Remarks: all the procedure in step 2 is work in iOS build but fail in android build.
2.5 https://docs.unity3d.com/Packages/com.unity.xr.management#4.0/manual/index.html
Tried XRSettings.LoadDeviceByName("none"); XRSettings.LoadDeviceByName(""); XRSettings.LoadDeviceByName("None");
Make sure that ''none'' is first in your VR SDK's, Then Cardboard.
I see a problem with your compare, there is no value
if (string.Compare(XRSettings.loadedDeviceName, "", true) != 0) {
If I understand correctly what you want to do, this code down here will receive a device name and will trigger the LoadDevice couroutine with this name.
public void VerifyDeviceName(string newDeviceName)
{
if (newDeviceName == "none")
{
Debug.Log("Will load none device");
StartCoroutine(LoadDevice(newDeviceName));
}
if (newDeviceName == "cardboard")
{
Debug.Log("Will load cardboard device");
StartCoroutine(LoadDevice(newDeviceName));
}
else
{
Debug.Log("Can't find device with name " + newDeviceName);
}
}
IEnumerator LoadDevice(string newDeviceName)
{
XRSettings.LoadDeviceByName(newDeviceName);
yield return new WaitForSeconds(10);
XRSettings.enabled = true;
Debug.Log("Loaded " + newDeviceName);
}
Note; This will obviously not work in editor you wil get a message saying you cannot trigger on/off vr in editor mode.
I just got through this by brute forcing it. The secret is not to Load device by name. If your trying to load "none" you should just initialize and deinitialize your XR loader.
Disable "Initialize XR on Startup" in Project Settings -> XR Plugin Management
In the code use these two methods
IEnumerator StartXR(){
yield return XRGeneralSettings.Instance.Manager.InitializeLoader();
if(XRGeneralSettings.Instance.Manager.activeLoader == null){
Debug.Log("initialization FAILED");
}
else{
XRGeneralSettings.Instance.Manager.activeLoader.Start();
}
}
void StopXR(){
XRGeneralSettings.Instance.Manager.activeLoader.Stop();
XRGeneralSettings.Instance.Manager.activeLoader.Deinitialize();
}
(Sorry I am terrable at code snippits! I'm new to answering)
Then call these as you need them. It should turn on and turn off XR in your project

How to turn on the torch/flashlight with GooglePlay Services Vision API Xamarin Android

I have been trying to implement the flashlight/torch feature of the camera using the GooglePlay Services Vision API (using Nuget from Visual Studio) for the past few days without success. I have noticed that there is a GitHub implementation of this API which has such functionality but that is only available to Java users.
I was wondering if there is anything related to C# Xamarin users.
The Camera object is not made available on this API therefore I am not able to alter the Camera parameters needed to activate the flashlight.
I would like to be sure if that functionality is not available so I don't waste more time over this. It just might be the case that the Xamarin developers have not attended to this functionality and they might in a near future.
UPDATE
https://github.com/googlesamples/android-vision/blob/master/visionSamples/barcode-reader/app/src/main/java/com/google/android/gms/samples/vision/barcodereader/BarcodeCaptureActivity.java
In there you can see that on line 214 we have such method call:
mCameraSource = builder.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null).build();
SetFlashMode is not a method of the CameraSource in Nuget, but it is on the GitHub (open source version).
Xamarin Vision Library Didn't expose the method to set Flash Mode.
WorkAround.
Using Reflection. You can get the Camera Object from CameraSouce and add the flash parameter then set the updated parameters to the camera.
This should be called after surfaceview has been created
Code
public Camera getCameraObject (CameraSource _camSource)
{
Field [] cFields = _camSource.Class.GetDeclaredFields ();
Camera _cam = null;
try {
foreach (Field item in cFields) {
if (item.Name.Equals ("zzbNN")) {
Console.WriteLine ("Camera");
item.Accessible = true;
try {
_cam = (Camera)item.Get (_camSource);
} catch (Exception e) {
Logger.LogException (this, e);
}
}
}
} catch (Exception e) {
Logger.LogException (this, e);
}
return _cam;
}
public void setFlash (bool isEnable)
{
try {
isTorch = !isEnable;
var _cam = getCameraObject (mCameraSource);
if (_cam == null) return;
var _pareMeters = _cam.GetParameters ();
var _listOfSuppo = _cam.GetParameters ().SupportedFlashModes;
_pareMeters.FlashMode = isTorch ? _listOfSuppo [0] : _listOfSuppo [3];
_cam.SetParameters (_pareMeters);
} catch (Exception e) {
Logger.LogException (this, e);
}
}
Basically, anything you can do with Android can be done with Xamarin.Android. All the underlying APIs area available.
Since you have existing Java code, you can create a binding project that enables you to call the code from your Xamarin.Android project. Here's a good article on how to get started: Binding a Java Library
On the other hand, I don't think you need a library to do what you want to. If you only want torch/flashlight functionality, you just need to adapt the Java code from this answer to work in Xamarin.Android with C#.

ERROR_WRONG_LABEL when trying to print wireless using Android Brother Sdk for label printer

I have trying to print using labels from my android app which using wifi commands Brother QL-720NW label printer. Since I performed factory reset on the printer , I'm getting this error
Problem: ERROR_WRONG_LABEL( means wrong roll specified in the sdk guide) error is thrown on print command, since I performed factory
reset on the printer .
CODE:
void printTemplateSample()
{
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
try{
// Retrieve printer informations
myPrinterInfo = myPrinter.getPrinterInfo();
// Set printer informations
myPrinterInfo.printerModel = PrinterInfo.Model.QL_720NW;
myPrinterInfo.port=PrinterInfo.Port.NET;
myPrinterInfo.printMode=PrinterInfo.PrintMode.FIT_TO_PAGE;
// :
myPrinterInfo.paperSize = PrinterInfo.PaperSize.A4;
myPrinterInfo.ipAddress="192.168.1.13";
myPrinterInfo.macAddress="00:80:92:BD:35:7D";
myPrinter.setPrinterInfo(myPrinterInfo);
// Start creating P-touch Template command print data
// myPrinter.startPTTPrint(1, null);
Boolean val= myPrinter.startPTTPrint(6, null);
Log.i("print", "startPTTPrint "+val);
// Replace text
myPrinter.replaceText("abcde");
// myPrinter.replaceText("12345");
// Trasmit P-touch Template command print data
PrinterStatus status=myPrinter.flushPTTPrint();//ERROR thrown here
Log.i("print", "PrinterStatus err"+status.errorCode);
}catch(Exception e){
e.printStackTrace();
}
}
I'm using there sample code from here
Objective - my ultimate objective is to replace text in template and print but currently I'm not able to print anything
I'm using this Brother SDK.
I tried the Brother sample code for android , it also gives the same error
BUT brother i print app and Ptouch software are successfully printing without any error.
Please help!
Thanks
I resolved this by creating a LabelInfo object, since you have a Label Printer. It's not clear at all in the documentation. You need to set the label info after the printer info.
PrinterInfo info = myPrinter.getPrinterInfo();
info.paperSize = PrinterInfo.PaperSize.CUSTOM;
LabelInfo mLabelInfo = new LabelInfo();
mLabelInfo.labelNameIndex = 5;
mLabelInfo.isAutoCut = true;
mLabelInfo.isEndCut = true;
mLabelInfo.isHalfCut = false;
mLabelInfo.isSpecialTape = false;
myPrinter.setPrinterInfo(info);
myPrinter.setLabelInfo(mLabelInfo);
The ERROR_WRONG_LABEL means that you have a wrong value in paperSize or labelNameIndex.
I have a P750W label printer with a 24'' paper. I found that value 5 is the good one for this size, but I don't know for your printer.
I had the same problem and figured out that you should specify the labelNameIndex field to the PrinterInfo object.
I had the QL-810W printer. I tried many values and nothing worked until I set it to:
printerInfo.labelNameIndex = LabelInfo.QL700.W62RB.ordinal // -> 17
I figured out the correct value by making a for loop with all integers from 0 to 100 and logging the result until the printing succeeded with this value. I know this is not the optimal solution but I can't find any documentation or reference for these codes.
Here is the code I used to specify the PrinterInfo object:
val printerInfo = PrinterInfo()
printerInfo.printerModel = PrinterInfo.Model.QL_810W
printerInfo.port = PrinterInfo.Port.NET
printerInfo.orientation = PrinterInfo.Orientation.PORTRAIT
printerInfo.paperSize = PrinterInfo.PaperSize.CUSTOM
printerInfo.align = PrinterInfo.Align.CENTER
printerInfo.valign = PrinterInfo.VAlign.MIDDLE
printerInfo.printMode = PrinterInfo.PrintMode.ORIGINAL
printerInfo.numberOfCopies = 1
printerInfo.labelNameIndex = LabelInfo.QL700.W62RB.ordinal // -> 17
printerInfo.isAutoCut = true
printerInfo.isCutAtEnd = false
return printerInfo
TL;DR
I solved by setting the workPath attribute:
printerInfo.workPath = context.cacheDir.Path
I noticed that the setPrinterInfo was returning false and when trying to print I received the WRONG_LABEL error code. Debugging the code I figured out that it's related to file writing permission that Brother SDK requires. The documentation is confusing and mentions about needing the WRITE_EXTERNAL_STORAGE if workPath isn't set. Even having this permission I could not make it work. I solved by setting the workPath attribute as shown above.

Categories

Resources