[Q] app for screencast - Android Q&A, Help & Troubleshooting

Hi,
im planning to use my tablet (no problem rooting also) for screen presentations in university. The computers at university are connected via wireless, my idea is to connect the pc from university to my tablet via browser and stream the content im changing in the tablet. I said via browser because we are not allowed to install any app on the computer.
Are there any apps that could do the job?

If your device is rooted you can simply use PICME, which serves screenshots via Http. You'll need to set up a slim JS wrapper to reload http://phoneIp:8082/snapshot.png over and over about once per second, but aside from that it would fit your needs perfectly.

Here's a very simple HTML file that you can use:
Code:
<!DOCTYPE html>
<html>
<head>
<title>Screencast</title>
<script>
var display=[null,null];
var ip;
var updateDelayMs=5000;
var currentBuffer=1;
function switchBuffer(){
display[currentBuffer].style.visibility="hidden";
currentBuffer=1-currentBuffer;
display[currentBuffer].style.visibility="visible";
window.setTimeout(function(){
display[1-currentBuffer].src="http://"+ip+":8082/snapshot.png?"+Math.random();
},updateDelayMs);
};
window.onload=function(){
display[0]=document.getElementById("display1");
display[1]=document.getElementById("display2");
ip=window.prompt("Please enter your Android device's IP in the form x.x.x.x");
display[0].onload=display[1].onload=switchBuffer;
display[0].src="http://"+ip+":8082/snapshot.png?"+Math.random();
};
</script>
<style>
.display{
position:absolute;
top:0px;
left:0px;
visibility:hidden;
}
</style>
</head>
<body>
<img src="" class="display" id="display1" />
<img src="" class="display" id="display2" />
</body>
</html>

Related

[Q] Calling Webservice from Android browser(Android 2.2) using html5 does not work

Hi,
I have been working on calling a simple web service in html5 from Android Browser(Android 2.2). Its not working on Android browser. But, it works if i run it on a PC. Nothing happens when i click the button. I have been on net for couple of weeks now. But, didn't get anything to work. Below is the code of the html page. please help.
<html>
<head>
<title>UseSwap</title>
<script language="JavaScript">
function InitializeService(){
service.useService("h t t p://localhost:2913/WebServicesUsingCSharp/WebService.asmx?wsdl",
"GetAgeService");
}
var StrYear, StrMonth, StrDay;
function GetAge(){
StrYear = document.DemoForm.StringYear.value;
StrMonth = document.DemoForm.StringMonth.value;
StrDay = document.DemoForm.StringDay.value;
service.GetAgeService.callService("GetAge", StrYear, StrMonth, StrDay);
}
function ShowResult(){
alert(event.result.value);
}
</script>
</head>
<body onload="InitializeService()" id="service"
style="behavior:url(webservice.htc)" onresult="ShowResult()">
<form name="DemoForm">
Year : <input type="text" name="StringYear"/>
Month : <input type="text" name="StringMonth"/>
Day : <input type="text" name="StringDay"/>
<button onclick="GetAge()">Get Age</button>
</form>
</body>
</html>
Regards,
Parashant.

Images in RSS (Flash Builder 4.5)

Hello all!
I really need help, because I`m not a programmer, but I make a very simple RSS reader for my website in Flash Builder 4.5, based on this tutorial. Now I have a problem. I need to put images into articles in application (DetailsView). In my RSS feed images in <enclosure> tag. I have no idea how put images in DetailsView and how to get it with enclosure tag.
Please, I really need this and I very greatful for any help!
This is source coude for DetailsView:
Code:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:rssreader="services.rssreader.*"
title="" viewActivate="getDetails()">
<fx:Script>
<![CDATA[
import valueObjects.Item;
[Bindable] private var rtitle:String;
[Bindable] private var rdate:String;
[Bindable] private var rcreator:String;
[Bindable] private var rlink:String;
[Bindable] private var rdesc:String;
private function getDetails():void
{
var p:RegExp = /(")/ig;
var thisItem:Item = data as Item;
rtitle = thisItem.title;
rdate = thisItem.pubDate;
rcreator = thisItem.author;
rlink = thisItem.link;
rdesc = thisItem.description;
rtitle = rtitle.replace(p, "");
}
]]>
</fx:Script>
<fx:Declarations>
<s:CallResponder id="getDataResult"/>
<rssreader:Rssreader id="rssreader"/>
</fx:Declarations>
<s:navigationContent>
<s:Button label="Nazaj" click="navigator.popView()" />
</s:navigationContent>
<s:BorderContainer top="0" bottom="0" left="0" right="0"
backgroundColor="#FFFFFF">
<s:Label left="20" right="20" top="42" height="61"
backgroundColor="#FFFFFF" color="#000000" fontSize="24"
paddingBottom="20" paddingLeft="5" paddingRight="5"
paddingTop="5" text="{rtitle}"/>
<s:Label left="20" right="90" top="14" height="23" backgroundColor="#FEFDFD" color="#666666"
fontSize="18" fontStyle="italic" paddingBottom="5" paddingLeft="5" paddingRight="5"
paddingTop="5" text="{rdate}"/>
<s:BitmapImage y="91" left="20" right="20" height="135" source="image"/>
<s:Label left="20" right="20" top="335" bottom="69" color="#666666"
backgroundColor="#FFFFFF" fontSize="18" paddingBottom="5"
paddingLeft="5" paddingRight="5" paddingTop="5"
text="{rdesc}" maxDisplayedLines="50" />
<s:Button left="50" right="50" bottom="22" label="Preberi celoten članek"
click="navigator.pushView(ClanekHTML, data.link)"/>
</s:BorderContainer>
</s:View>
And this is link to my rss feed: http://www.elektro-vozila.si/rssnovice
I found this http://www.telexer.nl/code-snippets/retrieve-images-from-rss-all-of-them/2/ but how to put this code into my code?
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A
OK, thx for move topic. Anyone in this section have a solution for my problem?
Please, anyone with solution for this problem?

[Q] Android Dev help please- my activity stack isnt behaving and i dont know why!

I am going out of my mind trying to work out why one of my activities is not working correctly with the stack.back button.
Activity Brain is launched when the user presses an image button in Main activity, this works fine and the back button behaves as expected from Brain (ie it returns to main activity as expected).
Within brain i want to launch a PDF based on which image button the user presses, I am doing this via URI with the code below, the PDF loads fine, but when back is pressed within acrobat the app returns to Main activity and not the brain which is not the behaviour i want (or expected). I have read the app developers guide and tried all options with Intent Flag_activity (i think) but have not been able to fix the back button behaviour. I have tried linking to different PDFs (in case it was something random in acrobat) but the app behaves the same, always going back to main and not the brain that I want.
I am using Imagebuttons to allow the user to select the pdfs and the code below is calling the URI / intent to display the pdf. I have left in 2 of the Intent.Flags I have tried and had no luck with for amplification, I had expected Intent.Flag_Activity_Clear_Top to work, but i must have missed something.
Brain activity is called from main using the following onClick code
Code:
if (v==bbrain) {
Intent startbrain = new Intent(Main.this, Brain.class); //this is the Brain chooser
startActivity(startbrain);
overridePendingTransition(R.anim.pull_from_left_enter, R.anim.pull_out_to_left_exit);
}
Then brain activity java looks like this:
public void onClick(View v) {
if (v==bhome); {
Intent starthome = new Intent(Brain.this, Main.class); //this is main screen
startActivity(starthome);
overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
}
if (v==babouttest){
Intent start1gp = new Intent(Brain.this, AboutScreen.class); //this is 1gp lesson
startActivity(start1gp);
overridePendingTransition(R.anim.pull_from_left_enter, R.anim.pull_out_to_left_exit);
}
if (v==imagepetro) {
File file = new File("/sdcard/documents/1.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
}
catch (ActivityNotFoundException e) {
}
}
} //end of load
if (v==imagesteam) {
File file = new File("/sdcard/documents/2.pdf");
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
}
catch (ActivityNotFoundException e) {
}
}
} //end of load
}
//menu inflator bits
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_brain, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am not sure if i have missed something elsewhere when writing this app? Below is the brain and main activity sections out of the manifest if that makes any difference
Code:
<activity
android:name=".Main"
android:label="@string/title_activity_main"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<!-- <category android:name="android.intent.category.LAUNCHER" /> -->
</intent-filter>
</activity>
<activity
android:name=".Brain"
android:label="@string/title_activity_brain"
android:screenOrientation="landscape" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.trainer.Main" />
</activity>
I am totally out of ideas why this code isnt working, i am launching PDFs from elsewhere in other activities and the URI way has worked fine, I am missing something but hopefully a fresh pair of eyes will spot what I cant!
So following this post here http://stackoverflow.com/questions/2442713/view-the-tasks-activity-stack
my activity stack prints out as follows from main to brain activity (correctly)
Code:
Running activities (most recent first):
Run #3: ActivityRecord{41cd3948 u0 com.trainer/.Brain}
Run #2: ActivityRecord{41ca29a0 u0 com.trainer/.Main}
Run #1: ActivityRecord{41a2c5d8 u0 com.cyanogenmod.trebuchet/.Launcher}
so all good so far I think, but when I launch any of the pdfs from the brain activity this is the resultant activity stack:
Code:
Run #5: ActivityRecord{4154ca00 u0 com.adobe.reader/.ARViewer}
Run #4: ActivityRecord{41bcbcf8 u0 com.trainer/.Main}
Run #3: ActivityRecord{41cd3948 u0 com.trainer/.Brain}
Run #2: ActivityRecord{41ca29a0 u0 com.trainer/.Main}
Run #1: ActivityRecord{41a2c5d8 u0 com.cyanogenmod.trebuchet/.Launcher}
So for some reason opening the PDF starts another version of the main activity, btu I have no idea at all why this is happening? Hopefully this means something to someone else?
Thanks for any help that can be offered on this....
Hopefully I have provided enough detail, if not please let me know what I should include. Thanks for any help, Andy

Sams. Gear S watch-face WEB APP , problem when implentation MaterialDisign Google fnt

Hi there,
"Samsung Gear S watch-face S watch-face, problem when implentation MaterialDisign Google fonts "
Gear S watch-face on Tizen WEB APP
Try to make implentation( self hosting) MaterialDisign Google fonts and have a some problems:
CSS
.......
.....
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(../css/fonts/MaterialIcons-Regular.eot); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
url(../css/fonts/MaterialIcons-Regular.woff2) format('woff2'),
url(../css/fonts/MaterialIcons-Regular.woff) format('woff'),
url(../css/fonts/MaterialIcons-Regular.ttf) format('truetype');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 36px; /* Preferred icon size */
display: inline-block;
width: 1em;
height: 1em;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
position: absolute;
left: 150px;
top: 100px;
color: rgba(255, 255, 255, 1);
text-rendering: optimizeSpeed;
}
...
HTML:
...
THAT WORK :
<div class="material-icons batteryyc" id="batteryy"></div>
NOT WORK (crash CSS of the page app):
<div class="material-icons batteryyc" id="batteryy">battery_charging_full</div>
..
Not WORK: JS+HTML:
.....
<div class="material-icons md-18 batteryyc" id="batteryy"></div>
..
document.getElementById("batteryy").textContent ="";
...
Why on screen browser work as one old IE?
Google DOCs:
https://www.google.com/design/icons/#ic_battery_charging_full
http://google.github.io/material-design-icons/
It’s easy to incorporate icons into your web page. Here’s a small example:
<i class="material-icons">face</i>
For browsers that do not support ligatures, fall back to specifying the icons using numeric character references like the example below:
<i class="material-icons"></i>
etc
PLZ HLP
news
News;
I have one replay in the other website about tizen:
"17 aoû 2015 11:02
Hi,
It seems that Tizen doesn't support ligature for now. I'm expecting that it will support it soon.
Regards"
news 2 , Q2
Okay , i'm find one solution for make some code with MD icons in watchface, but MD-BADGES still on the "dark side" ))
DOCS: http://www.getmdl.io/components/index.html#badges-section
try to make this test code in the HTML of the watch face and look were is bages?
HTML:
<html>
<head>
<!-- Material Design Lite -->
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.3/material.min.js"></script>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.3/material.brown-deep_orange.min.css" />
<!-- Material Design icon font -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<br>
<br>
<div class="material-icons mdl-badge mdl-badge--no-background" data-badge="99">sms</div>
<br>
<em class="material-icons mdl-badge" data-badge="99"></em>
<br>
<i class="material-icons"></i>
<br>
<br>
</body>
</html>

The Ultimate Scanning App From Huawei

Have you ever wanted to be able to scan and create 13+ different types of barcodes from your app? Hopefully you have, otherwise I'm not sure why you're reading this. If you do, then Huawei has an SDK for you: Scan Kit.
Scan Kit allows you to scan and generate various different one-dimensional and two-dimensional barcodes with ease, and you don't even need a Huawei device to use it.
Interested? No? Well, get interested. Now? Good. Let's get started.
Preparation
First up, make sure you have a Huawei Developer Account. This process can take a couple days, and you'll need one to use this SDK, so be sure to start that as soon as possible. You can sign up at https://developer.huawei.com.
Next, you'll want to obtain the SHA-256 representation of your app's signing key. If you don't have a signing key yet, be sure to create one before continuing. To obtain your signing key's SHA-256, you'll need to use Keytool which is part of the JDK installation. Keytool is a command-line program. If you're on Windows, open CMD. If you're on Linux, open Terminal.
On Windows, you'll need to "cd" into the directory containing the Keytool executable. For example, if you have JDK 1.8 v231 installed, Keytool will be located at the following path:
Code:
C:\Program Files\Java\jdk1.8.0_231\bin\
Once you find the directory, "cd" into it:
Code:
C: #Make sure you're in the right drive
cd C:\Program Files\Java\jdk1.8.0_231\bin\
Next, you need to find the location of your keystore. Using Android's debug keystore as an example, where the Android SDK is hosted on the "E:" drive in Windows, the path will be as follows:
Code:
E:\AndroidSDK\.android\debug.keystore
(Keytool also supports JKS-format keystores.)
Now you're ready to run the command. On Windows, it'll look something like this:
Code:
keytool -list -v -keystore E:\AndroidSDK\.android\debug.keystore
On Linux, the command should be similar, just using UNIX-style paths instead.
Enter the keystore password, and the key name (if applicable), and you'll be presented with something similar to the following:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Make note of the SHA256 field.
SDK Setup
Now we're ready to add the Scan Kit SDK to your Android Studio project. Go to your Huawei Developer Console and click the HUAWEI AppGallery tile. Agree to the terms of use if prompted.
Click the "My projects" tile here. If you haven't already added your project to the AppGallery, add it now. You'll be asked for a project name. Make it something descriptive so you know what it's for.
Now, you should be on a screen that looks something like the following:
Click the "Add app" button. Here, you'll need to provide some details about your app, like its name and package name.
Once you click OK, some SDK setup instructions will be displayed. Follow them to get everything added to your project.
You'll also need to add one of the following to the "dependencies" section of your app-level build.gradle file:
Code:
implementation 'com.huawei.hms:scan:1.2.0.301'
implementation 'com.huawei.hms:scanplus:1.2.0.301'
The difference between these dependencies is fairly simple. The basic Scan Kit SDK is only about 0.8MB in size, while the Scan Kit Plus SDK is about 3.3MB. The basic SDK will function identically to the Plus SDK on Huawei devices. On non-Huawei devices, you'll lose the enhanced recognition capabilities with the basic SDK.
If your app has size restrictions, and you only need basic QR code recognition, then the basic SDK is the best choice. Otherwise, pick the Plus SDK.
If you ever need to come back to these instructions, you can always click the "Add SDK" button after "App information" on the "Project setting" page.
Now you should be back on the "Project setting" page. Find the "SHA-256 certificate fingerprint" field under "App information," click the "+" button, and paste your SHA-256.
Now, if you're using obfuscation in your app, you'll need to whitelist a few things for HMS to work properly.
For ProGuard:
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
For AndResGuard:
Code:
"R.string.hms*",
"R.string.agc*",
"R.string.connect_server_fail_prompt_toast",
"R.string.getting_message_fail_prompt_toast",
"R.string.no_available_network_prompt_toast",
"R.string.third_app_*",
"R.string.upsdk_*",
"R.layout.hms*",
"R.layout.upsdk_*",
"R.drawable.upsdk*",
"R.color.upsdk*",
"R.dimen.upsdk*",
"R.style.upsdk*
That's it! The Scan Kit SDK should now be available in your project.
Basic Usage
In order to properly use Scan Kit, you'll need to declare some permissions in your app:
XML:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
These are both dangerous-level permissions, so make sure you request access to them at runtime on Marshmallow and later.
You should also declare a couple required device features, to make sure distribution platforms can hide your app on incompatible devices:
XML:
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Now that you've got the permissions and features declared, it's time to start scanning. There are four modes you can use: Default View, Customized View, Bitmap, and MultiProcessor.
Default View
The Default View is the quickest way to get set up and running. Scan Kit provides the UI and does all the scanning work for you. This mode is able to scan barcodes live through the camera viewfinder, or by scanning existing images.
The first thing you'll need to do to use this is to declare the Scan Kit's scanner Activity in your Manifest:
XML:
<activity android:name="com.huawei.hms.hmsscankit.ScanKitActivity" />
Next, simply call the appropriate method to start the Activity. This must be done from an Activity context, since it makes use of Android's onActivityResult() API.
Code:
//The options here are optional. You can simply pass null
//to the startScan() method below.
//This is useful if you're only looking to scan certain
//types of codes. Scan Kit currently supports 13. You can
//see the list here: https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/barcode-formats-supported-0000001050043981-V5
val options = HmsScanAnalyzerOptions.Creator()
.setHmsScanTypes(
HmsScan.QRCODE_SCAN_TYPE,
HmsScan.DATAMATRIX_SCAN_TYPE
)
.create()
ScanUtil.startScan(activity, REQUEST_CODE, options)
Now you just need to handle the result:
Code:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != Activity.RESULT_OK || data == null) {
//Scanning wasn't successful. Nothing to handle.
return
}
if (requestCode == REQUEST_CODE) {
//Scan succeeded. Let's get the data.
val hmsScan = data.getParcelableExtra<HmsScan>(ScanUtil.RESULT)
if (hmsScan != null) {
//Handle appropriately.
}
}
}
We'll talk more about handling the result later.
Customized View
Customized View is similar to Default View in that Scan Kit will handle the scanning logic for you. The difference is that this mode lets you create your own UI. You're also limited to using the live viewfinder.
The following code should be placed inside your Activity's onCreate() method:
Code:
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scan)
//A ViewGroup to hold the scanning View that HMS will create
val container = findViewById<FrameLayout>(R.id.scanning_container)
//The position/size of the scanning area inside the scanning
//View itself. This is optional.
val scanBounds = Rect()
//The scanning View itself.
val scanView = RemoteView.Builder()
.setContext(this)
.setBoundingBox(scanBounds) //optional
.setFormat(HmsScan.QR_SCAN_TYPE) //optional, accepts a vararg of formats
.build()
//Initialize the scanning View.
scanView.onCreate(savedInstanceState)
container.addView(scanView)
scanView.setOnResultCallback { result ->
//`result` is an Array<HmsScan>
//Handle accordingly.
}
}
We'll talk about how to handle the HmsScan object later.
In a real application, the "scanView" variable should be a global variable. It's lifecycle-aware, so it has all the lifecycle methods, which you should probably call:
Code:
override fun onStart() {
super.onStart()
scanView.onStart()
}
//etc
Bitmap
This mode is useful if you have a Bitmap and you want to decode it. You can get that Bitmap however you want. All that matters is that you have one.
The example below shows how to obtain a Bitmap either from a camera capture frame or from an existing image in internal storage, and how to pass that Bitmap to Scan Kit for processing.
Code:
val img = YuvImage(
//A byte array representation of an image.
data,
//Depends on your image type: https://developer.android.com/reference/android/graphics/ImageFormat
ImageFormat.NV21,
//The width of the image data.
width,
//The height of the image data.
height
)
val stream = ByteArrayOutputStream()
//Copy the data to an output stream.
img.compressToJpeg(
//Size of the JPEG, in a Rect representation.
Rect(0, 0, width, height),
//Quality.
100,
//Output stream.
stream
)
//Create a Bitmap
val bmp = BitmapFactory.decodeByteArray(
stream.asByteArray(),
0,
stream.asByteArray().size
)
//If you want to use a pre-existing image, just obtain
//a Bitmap for that. This example would be placed in
//onActivityResult() after using ACTION_GET_CONTENT for an image.
val bmp = MediaStore.Images.Media.getBitmap(contentResolver, data.data)
//Set up the options.
val options = HmsScanAnalyzerOptions.Creator()
//Scan types are optional.
.setHmsScanTypes(
HmsScan.QRCODE_SCAN_TYPE,
HmsScan.DATAMATRIX_SCAN_TYPE
)
//If you're retrieving a Bitmap from an existing photo,
//set this to `true`.
.setPhotoMode(false)
.create()
//Send the scanning request and get the result.
val scans: Array<HmsScan> = ScanUtil.decodeWithBitmap(context, bmp, options)
if (!scans.isNullOrEmpty()) {
//Scanning was successful.
//Check individual scanning results.
scans.forEach {
//Handle.
//If zoomValue != 1.0, make sure you update
//the focal length of your camera interface,
//if you're using a camera. See Huawei's
//documentation for details on this.
//https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-bitmap-camera-0000001050042014
val zoomValue = it.zoomValue
}
}
We'll go over how to handle the HmsScan later on.
MultiProccessor
The MultiProcessor mode supports both existing images and using a viewfinder. It can take image frames and analyze them using machine learning to simultaneously detect multiple barcodes, along with other objects, like faces.
There are two ways to implement this mode: synchronously, and asychronously.
Here's an example showing how to implement it synchronously.
Code:
//Create the options (optional).
val options = HmsScanAnalyzerOptions.Creator()
.setHmsScanTypes(
HmsScan.QRCODE_SCAN_TYPE,
HmsScan.DATAMATRIX_SCAN_TYPE
)
.create()
//Set up the barcode detector.
val barcodeDetector = HmsScanAnalyzer(options /* or null */)
//You'll need some sort of Bitmap reference.
val bmp = /* However you want to obtain it */
//Convert that Bitmap to an MLFrame.
val frame = MLFrame.fromBitmap(bmp)
//Analyze and handle result(s).
val results: SparseArray<HmsScan> = barcodeDetector.analyseFrame(frame)
results.forEach {
//Handle accordingly.
}
To analyze asynchronously, just change the method called on "barcodeDetector":
Code:
barcodeDetector.analyzInAsyn(frame)
.addOnSuccessListener { scans ->
//`scans` is a List<HmsScan>
scans?.forEach {
//Handle accordingly.
}
}
.addOnFailureListener { error ->
//Scanning failed. Check Exception.
}
Parsing Barcodes
It's finally time to talk about parsing the barcodes! Yay!
The HmsScan object has a bunch of methods you can use to retrieve information about barcodes scanned by each method.
Code:
val scan: HmsScan = /* some HmsScan instance */
//The value contained in the code. For instance,
//if it's a QR code for an SMS, this value will be
//something like: "smsto:1234567890:Hi!".
val originalValue = scan.originalValue
//The type of code. For example, SMS_FORM, URL_FORM,
//or WIFI_CONNTENT_INFO_FORM. You can find all the forms
//here: https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/scan-hms-scan4-0000001050167739-V5.
val scanTypeForm = scan.scanTypeForm
//If it's a call or SMS, you can retrieve the
//destination phone number. This will be something
//like "1234567890".
val destPhoneNumber = scan.destPhoneNumber
//If it's an SMS, you can retrieve the message
//content. This will be something like "Hi!".
val smsContent = scan.smsContent
There are plenty more methods in the HmsScan class to help you parse various barcodes. You can see them all in Huawei's API reference.
Barcode Generation
Finally, let's talk about how to make your own barcodes using Scan Kit. This example will show you how to make a QR code, although you should be able to create any of the formats supported by Scan Kit.
Code:
//The code's content.
val content = "Some Content"
//Can be any supported type.
val type = HmsScan.QRCODE_SCAN_TYPE
//Output dimensions.
val width = 400
val height = 400
//Create the options.
val options = HmsBuildBitmapOption.Creator()
//The background of the barcode image. White is the default.
.setBitmapBackgroundColor(Color.RED)
//The color of the barcode itself. Black is the default
.setBitmapColor(Color.BLUE)
//Margins around the barcode. 1 is the default.
.setBitmapMargin(3)
.create()
try {
//Build the output Bitmap.
val output = ScanUtil.buildBitmap(content, type, width, height, options)
//Save it to internal storage, upload it somewhere, etc.
} catch (e: WriterException) {
//Creation failed. This can happen if one of the arguments for `buildBitmap()` is invalid.
}
Conclusion
And that's it!
Scan Kit is a powerful SDK that doesn't even require a Huawei device to work. Hopefully, this guide helped you get up and running. For more details on implementation, along with the API reference, be sure to check out Huawei's full documentation.

Categories

Resources