What is Motivation Description? - Android Design Resources

How to make your app accessible to users with vision impairment or other physical disabilities.
Your customer base probably includes many people with disabilities, whether you are aware of it or not. According to government figures, one person in five has some functional limitation, and eight percent of all users on the Web have disabilities. In the United States alone there are more than 30 million people with disabilities who can be affected by the design of computer software, and worldwide the number is much higher. Many countries/regions, including the United States, have laws that mandate accessibility at some level.
When it comes to reaching as wide a user base as possible, it's important to pay attention to accessibility in your Android application. Cues in your user interface that may work for a majority of users, such as a visible change in state when a button is pressed, can be less optimal if the user is visually impaired.
This post shows you how to make the most of the accessibility features built into the Android framework. It covers how to optimize your app for accessibility, leveraging platform features like focus navigation and content descriptions. It also covers how to build accessibility services, that can facilitate user interaction with any Android application, not just your own.
Techniques should be applied to solve them:
1. Developing Accessible Applications
Learn to make your Android application accessible. Allow for easy navigation with a keyboard or directional pad, set labels and fire events that can be interpreted by an accessibility service to facilitate a smooth user experience.
Add Content Descriptions
It's easy to add labels to UI elements in your application that can be read out loud to your user by a speech-based accessibility service like TalkBack . If you have a label that's likely not to change during the lifecycle of the application (such as "Pause" or "Purchase"), you can add it via the XML layout, by setting a UI element's android:contentDescription attribute, like in this example:
<Button
android:id=”@+id/pause_button”
android:src=”@drawable/pause”
android:contentDescription=”@string/pause”/>
However, there are plenty of situations where it's desirable to base the content description on some context, such as the state of a toggle button, or a piece selectable data like a list item. To edit the content description at runtime, use the setContentDescription() method, like this:
String contentDescription = "Select " + strValues[position];
label.setContentDescription(contentDescription);
Try to add content descriptions wherever there's useful information, but avoid the web-developer pitfall of labelling everything with useless information. For instance, don't set an application icon's content description to "app icon". That just increases the noise a user needs to navigate in order to pull useful information from your interface.
Try it out! Download TalkBack (an accessibility service published by Google) and enable it in Settings > Accessibility > TalkBack. Then navigate around your own application and listen for the audible cues provided by TalkBack.
Design for Focus Navigation
Your application should support more methods of navigation than the touch screen alone. Many Android devices come with navigation hardware other than the touchscreen, like a D-Pad, arrow keys, or a trackball. In addition, later Android releases also support connecting external devices like keyboards via USB or bluetooth.
In order to enable this form of navigation, all navigational elements that the user should be able to navigate to need to be set as focusable. This modification can be done at runtime using the View.setFocusable() method on that UI control, or by setting the android:focusable attrubute in your XML layout files.
Also, each UI control has 4 attributes, android:nextFocusUp, android:nextFocusDown, android:nextFocusLeft, and android:nextFocusRight, which you can use to designate the next view to receive focus when the user navigates in that direction. While the platform determines navigation sequences automatically based on layout proximity, you can use these attributes to override that sequence if it isn't appropriate in your application.
For instance, here's how you represent a button and label, both focusable, such that pressing down takes you from the button to the text view, and pressing up would take you back to the button.
<Button android:id="@+id/doSomething"
android:focusable="true"
android:nextFocusDown=”@id/label”
... />
<TextView android:id="@+id/label"
android:focusable=”true”
android:text="@string/labelText"
android:nextFocusUp=”@id/doSomething”
... />
Fire Accessibility Events
If you write a custom view, make sure it fires events at the appropriate times. Generate events by calling sendAccessibilityEvent(int), with a parameter representing the type of event that occurred. A complete list of the event types currently supported can be found in the AccessibilityEvent reference documentation.
As an example, if you want to extend an image view such that you can write captions by typing on the keyboard when it has focus, it makes sense to fire an TYPE_VIEW_TEXT_CHANGED event, even though that's not normally built into image views. The code to generate that event would look like this:
public void onTextChanged(String before, String after) {
...
if (AccessibilityManager.getInstance(mContext).isEnabled()) {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
}
...
}
Test Your Application
Be sure to test the accessibility functionality as you add it to your application. In order to test the content descriptions and Accessibility events, install and enable an accessibility service. One option is Talkback , a free, open source screen reader available on Google Play. With the service enabled, test all the navigation flows through your application and listen to the spoken feedback.
2. Developing Accessibility Services
Develop an accessibility service that listens for accessibility events, mines those events for information like event type and content descriptions, and uses that information to communicate with the user. The example will use a text-to-speech engine to speak to the user.
Create Your Accessibility Service
An accessibility service can be bundled with a normal application, or created as a standalone Android project. The steps to creating the service are the same in either situation. Within your project, create a class that extends AccessibilityService.
package com.example.android.apis.accessibility;
import android.accessibilityservice.AccessibilityService;
public class MyAccessibilityService extends AccessibilityService {
...
@override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
@override
public void onInterrupt() {
}
...
}
Like any other service, you also declare it in the manifest file. Remember to specify that it handles the android.accessibilityservice intent, so that the service is called when applications fire an AccessibilityEvent.
<application ...>
...
<service android:name=".MyAccessibilityService">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
. . .
</service>
...
</application>
If you created a new project for this service, and don't plan on having an application, you can remove the starter Activity class (usually called MainActivity.java) from your source. Remember to also remove the corresponding activity element from your manifest.
Configure Your Accessibility Service
You have two options for how to set these variables. The backwards-compatible option is to set them in code, using setServiceInfo(android.accessibilityservice.AccessibilityServiceInfo). To do that, override the onServiceConnected() method and configure your service in there. @override
public void onServiceConnected() {
// Set the type of events that this service wants to listen to. Others
// won't be passed to this service.
info.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED |
AccessibilityEvent.TYPE_VIEW_FOCUSED;
// If you only want this service to work with specific applications, set their
// package names here. Otherwise, when the service is activated, it will listen
// to events from all applications.
info.packageNames = new String[]
{"com.example.android.myFirstApp", "com.example.android.mySecondApp"};
// Set the type of feedback your service will provide.
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
// Default services are invoked only if no package-specific ones are present
// for the type of AccessibilityEvent generated. This service *is*
// application-specific, so the flag isn't necessary. If this was a
// general-purpose service, it would be worth considering setting the
// DEFAULT flag.
// info.flags = AccessibilityServiceInfo.DEFAULT;
info.notificationTimeout = 100;
this.setServiceInfo(info);
}
The second option is to configure the service using an XML file. Certain configuration options like canRetrieveWindowContent are only available if you configure your service using XML. The same configuration options above, defined using XML, would look like this:
<accessibility-service
android: accessibilityEventTypes="typeViewClicked|typeViewFocused"
android: packageNames="com.example.android.myFirstApp, com.example.android.mySecondApp"
android: accessibilityFeedbackType="feedbackSpoken"
android: notificationTimeout="100"
android: settingsActivity="com.example.android.apis.accessibility.TestBackActivity"
android: canRetrieveWindowContent="true"
/>
If you go the XML route, be sure to reference it in your manifest, by adding a <meta-data> tag to your service declaration, pointing at the XML file. If you stored your XML file in res/xml/serviceconfig.xml, the new tag would look like this:
<service android:name=".MyAccessibilityService">
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data android:name="android.accessibilityservice"
android:resource="@xml/serviceconfig" />
</service>
Respond to AccessibilityEvents
Now that your service is set up to run and listen for events, write some code so it knows what to do when an AccessibilityEvent actually arrives! Start by overriding the onAccessibilityEvent(AccessibilityEvent) method. In that method, use getEventType() to determine the type of event, and getContentDescription() to extract any label text associated with the view that fired the event. @override
public void onAccessibilityEvent(AccessibilityEvent event) {
final int eventType = event.getEventType();
String eventText = null;
switch(eventType) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
eventText = "Focused: ";
break;
case AccessibilityEvent.TYPE_VIEW_FOCUSED:
eventText = "Focused: ";
break;
}
eventText = eventText + event.getContentDescription();
// Do something nifty with this text, like speak the composed string
// back to the user.
speakToUser(eventText);
...
}
Query the View Heirarchy for More Context
This step is optional, but highly useful. The Android platform provides the ability for an AccessibilityService to query the view hierarchy, collecting information about the UI component that generated an event, and its parent and children. In order to do this, make sure that you set the following line in your XML configuration:
android:canRetrieveWindowContent="true"
Once that's done, get an AccessibilityNodeInfo object using getSource(). This call only returns an object if the window where the event originated is still the active window. If not, it will return null, so behave accordingly. The following example is a snippet of code that, when it receives an event, does the following:
.Immediately grab the parent of the view where the event originated
.In that view, look for a label and a check box as children views
.If it finds them, create a string to report to the user, indicating the label and whether it was checked or not.
.If at any point a null value is returned while traversing the view hierarchy, the method quietly gives up.
// Alternative onAccessibilityEvent, that uses AccessibilityNodeInfo @override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null) {
return;
}
// Grab the parent of the view that fired the event.
AccessibilityNodeInfo rowNode = getListItemNodeInfo(source);
if (rowNode == null) {
return;
}
// Using this parent, get references to both child nodes, the label and the checkbox.
AccessibilityNodeInfo labelNode = rowNode.getChild(0);
if (labelNode == null) {
rowNode.recycle();
return;
}
AccessibilityNodeInfo completeNode = rowNode.getChild(1);
if (completeNode == null) {
rowNode.recycle();
return;
}
// Determine what the task is and whether or not it's complete, based on
// the text inside the label, and the state of the check-box.
if (rowNode.getChildCount() < 2 || !rowNode.getChild(1).isCheckable()) {
rowNode.recycle();
return;
}
CharSequence taskLabel = labelNode.getText();
final boolean isComplete = completeNode.isChecked();
String completeStr = null;
if (isComplete) {
completeStr = getString(R.string.checked);
} else {
completeStr = getString(R.string.not_checked);
}
String reportStr = taskLabel + completeStr;
speakToUser(reportStr);
}
Now you have a complete, functioning accessibility service. Try configuring how it interacts with the user, by adding Android's text-to-speech engine, or using a Vibrator to provide haptic feedback!
3. Accessibility Checklist
Learn how to test your app for accessibility.
Testing Accessibility Features
Testing of accessibility features such as TalkBack, Explore by Touch and accessibility Gestures requires setup of your testing device. This section describes how to enable these features for accessibility testing.
Testing audible feedback
Audible accessibility feedback features on Android devices provide audio prompts that speaks the screen content as you move around an application. By enabling these features on an Android device, you can test the experience of users with blindness or low-vision using your application.
Audible feedback for users on Android is typically provided by TalkBack accessibility service and the Explore by Touch system feature. The TalkBack accessibility service comes preinstalled on most Android devices and can also be downloaded for free from Google Play.
Testing with TalkBack
The TalkBack accessibility service works by speaking the contents of user interface controls as the user moves focus onto controls. This service should be enabled as part of testing focus navigation and audible prompts.
To enable the TalkBack accessibility service:
Launch the Settings application.
Navigate to the Accessibility category and select it.
Select Accessibility to enable it.
Select TalkBack to enable it.
Note: While TalkBack is the most available Android accessibility service for users with disabilities, other accessibility services are available and may be installed by users.
Testing with Explore by Touch
The Explore by Touch system feature is available on devices running Android 4.0 and later, and works by enabling a special accessibility mode that allows users to drag a finger around the interface of an application and hear the contents of the screen spoken. This feature does not require screen elements to be focused using an directional controller, but listens for hover events over user interface controls.
To enable Explore by Touch:
Launch the Settings application.
Navigate to the Accessibility category and select it.
Select the TalkBack to enable it.
Note: On Android 4.1 (API Level 16) and higher, the system provides a popup message to enable Explore by Touch. On older versions, you must follow the step below.
Return to the Accessibility category and select Explore by Touch to enable it.
Note: You must turn on TalkBack first, otherwise this option is not available.
Testing focus navigation
Focus navigation is the use of directional controls to navigate between the individual user interface elements of an application in order to operate it. Users with limited vision or limited manual dexterity often use this mode of navigation instead of touch navigation. As part of accessibility testing, you should verify that your application can be operated using only directional controls.
You can test navigation of your application using only focus controls, even if your test devices does not have a directional controller. The Android Emulator provides a simulated directional controller that you can use to test navigation. You can also use a software-based directional controller, such as the one provided by the Eyes-Free Keyboard to simulate use of a D-pad on a test device that does not have a physical D-pad.
Testing gesture navigation
Gesture navigation is an accessibility navigation mode that allows users to navigate Android devices and applications using specific gestures. This navigation mode is available on Android 4.1 (API Level 16) and higher.
Note: Accessibility gestures provide a different navigation path than keyboards and D-pads. While gestures allow users to focus on nearly any on-screen content, keyboard and D-pad navigation only allow focus on input fields and buttons.
To enable gesture navigation:
Enable both TalkBack and the Explore by Touch feature as described in the Testing with Explore by Touch. When both of these features are enabled, accessibility gestures are automatically enabled.
You can change gesture settings using Settings > Accessibility > TalkBack > Settings > Manage shortcut gestures.
Note: Accessibility services other than TalkBack may map accessibility gestures to different user actions. If gestures are not producing the expected actions during testing, try disabling other accessibility services before proceeding.

Related

[Q] OnClickListener vs. android:OnClick

I'm looking at both a book and the beginning projects on developers.android.com and have a question. Google is utilizing the android:nClick to handle the click event which then points to a public method for execution....but the book is setting up click listeners by setting a View with the buttons ID and then executing the setOnClickListener. OnClickListenver has one method called OnClick which is then executed.
//book
public class MyGame extends Activity implements OnClickListener {
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
My question. Which is the better way to handle the Button Click? In looking at what google does in the XML, it seems a helluva lot cleaner....but curious on what the advantage is for the other way (and I cannot think of any). Search of the site didn't yield anything.
I dunno if the methods have advantages between them, however, I prefer the androidnClick method since the code looks clearer
You usually want to use the onClick method, as there is no benefit to implementing the OnClickListener (only more effort and possible performance loss).
If you want things like long clicks or other events, you will have to implement that (or define an inline listener), as there is no xml tag for those.
I think the OnClickListener is actually only there for consistency with these other classes

[APP][ROOT] zTorch Adjustable and extremely bright Flashlight

EDIT: 11/15/2014
This post features version 2.x.x. It is a complete rewrite using Android Studio because importing the project from Eclipse didn't go too well.
For information on version 1.x.x , go to post #28
Downloads for both versions are at the bottom of this page.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
ZTORCH Features:
The goal of ZTorch is to be a extremely quick and lightweight app that does one thing and does it well without extra bloat or ridiculous permissions. ZTorch can vary the brightness of your phones LED and allow you to set brightness levels higher than possible anywhere else.
The Galaxy S4 is capable of 16 different levels of brightness (0-15). Compared to other Apps:
The stock "Assistive Light" that is featured with the phone only sets the level to 1.
The brightest AppStore Apps, such as TeslaLED, are able to set the brightness to a little less than half brightness, level 6.
Typically, flashlight apps take about a second to switch on the LED
ZTorch can adjust the LED in mere milliseconds.
ZTorch stays on when the screen is off and doesn't flicker when the screen switches off.
ZTorch works with the camera. Ever wanted to use the flashlight LED while recording a video or taking a picture? Now you can.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
ZTorch should work across all phones with root if the proper system file is on the phone. ZTorch scans for the following binaries below. If your device isn't supported and you know the path to the proper file, you can set that path in the apps preferences. This app has only ever been tested on the Galaxy S4, if you try it on a different phone, PLEASE let me know how it is!
Code:
"/sys/class/camera/flash/rear_flash", - For Galaxy s4
"/sys/class/camera/rear/rear_flash", - For Galaxy Note and maybe s3
"/sys/class/leds/flashlight/brightness," - HTC devices
"/sys/devices/platform/flashlight.0/leds/flashlight/brightness" - HTC devices
" /sys/class/leds/spotlight/brightness" - Motorolla Droid Devices
"/sys/class/leds/torch-flash/flash_light" - Motorolla Droid 2
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Screenshots from ZTORCH-beta-2.0.0.26.apk:
Main Activity as popup with widget shown in background.
{
"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"
}
Notification:
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Permissions:
ACCESS_SUPERUSER - To set the LED
RECEIVE_BOOT_COMPLETED - Sets LED to 0, allows for persistent notification, notification on bootup.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Version Information:
Download attached at bottom of post.
LATEST: Version 2.0.3.50: (Feb 24, 2015)
Notification now appears on boot if that setting is enabled
Separated BootReceiver from main broadcast receiver so disabling the boot receiver won't break the rest of the app.
Notification icon changed to support Lollipop.
Renamed some app refs.
Somehow cut 50kb from the app, it's now 100.6Kb. Considering the Icons take up 89.5Kb I'm kinda amazed.
I haven't got around to making an actual Settings activity. So features are the same from prior version.
Version 1.2.2: (Mar 3, 2014) All the features work but is less refined.
Version 1.3.0: (June 16,2014) Added TorchPlayer to act similar to PWM. All Features work.
Version 1.4.0 (June 20,2014) Switching speed was the priority in this version; the brightness can be changed in <3ms. I abandoned the very comprehensive and powerful Stericson RootTools library in favor of a purpose built class that toggles the flashlight. Warning: The notification doesn't work on API-19 Android 4.4+. Clicking it does nothing. I need to build a new version sometime.
For more info on version 1.x.x such as the screenshots, see post #28
ZTORCH-beta-2.0.0.28: (November 15,2014) Beta version does not yet have a settings or preference activity implemented as well as other nonessentials. To change settings in this version, see below. Changes include:
Entirely new MainActivity that's now in a Popup window
Entirely New and Fully Working Notification
Widget now fills the entire 1x1 grid. (Let me know if there's problems, I set the left and right margins to -23dp to do this)
Added Warn feature and Torch Fireball icon for when the brightness is higher than the Warn value.
Slider no longer lags while trying to effectively "make a strobe light" by not sending broadcasts, updating views, or saving the brightness until after you take your finger off.
Slider changes color based on level.
ZTORCH-beta-2.0.0.33optimized: Technically should be: 2.0.2.33(November 16,2014) Changes:
Adds RECEIVE_BOOT_COMPLETE permission.
Ongoing Notification is available in AppPrefs.xml
TapGuard enabled by default. (Widget ignores first tap to prevent accidental taps)
ZTORCH-optimizedbeta-2.0.3.41: (November 17,2014) Changes:
New Notification AppPrefs.
ongoingNotif (Can't swipe away, Persistent).
onPriority and offPriority (levels: -2, -1, 0, 1, 2 where 2 is PRIORITY_MAX)
Shell Command Text and Toggle Button updated instantly while slider moves.
ZTorchReceiver enables you to send commands from other apps such as Tasker. Available broadcasts listed further down.
Fixed Force Close if the Main Toggle button is pressed and root was denied or the device is unsupported. (Not like you can use the app like this anyway, but still)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
BETA Version Settings
I'm still trying to figure out how android implements preferences and preference fragments. So in the beta, there is none! To change a setting, get a file browser with root access such as ES File Explorer, then navigate to the location below and edit the file "LEDPrefs.xml"
Code:
/data/data/derekziemba.ztorch/shared_prefs/
Additionally there is another file, "AppPrefs.xml" where you will find app specific settings and be able to configure the Notification.
"LEDPrefs.xml" will look like this on ZTORCH-beta-2.0.0.28. Later versions will be slightly different. I recommend uninstalling the app before installing a new beta.
default - The value the torch will turn on at when Toggled or Enabled.
inc - increment. Value the notifications "+" and "-" will increase or decrease by and the Widget will increase at if multitap = true;
multitap - If true, on successive widget taps the brightness will increase by the inc value. If false, brightness will toggle to default value;
wait - For multitap and tapguard. Time in milliseconds between successive widget taps to increase brightness. If more time than this has passed, the LED will shut off.
tapguard - To prevent accidental widget taps turning on the LED. If true, the widget ignores the first tap and waits for a second tap, unless the LED is already on.
min - just leave at 0, this is the "off" value, it is here in case some phones are reversed
max - maximum value on slider and the max value you can increment to. Only the first 3 digits of this will ever be used, giving a max possible value of 999.
warn - value at which the torch turns from yellow to a fireball and the slider begins changing colors from blue to yellow to red.
lvl - Current Brightness. There is no way to retrieve the current LED level, so the last value is stored here
sys - the system binary that controls the LED;
mask - bitmask. The brightness level is bitwise AND'ed with this value before executing the shell command to prevent invalid values. If you need help configuring this, use windows calculator and set it to programmer mode on Integer then click the bits you want to use, then use the integer value given.
"AppPrefs.xml" settings:
enableTorchOnAppLaunch - If true, opening the app will automatically set the brightness to the default value listed in "LEDPrefs.xml". Default is "false"
persistentNotif - If true, the notification will be persistent and it cannot be swiped away. Default is "false"
showNotifOnBootComplete - Posts the notification when BOOT_COMPLETE is received for easy access. Use with persistentNotif to prevent swiping away. Default is "true"
Notification Priorities. There are 5: MIN(-2), LOW(-1), DEFAULT(0), HIGH(1), and MAX(2). More info here: http://developer.android.com/design/patterns/notifications.html#guidelines
notifPriorityTorchON - Notification Priority when the LED is on. Default is "2"
notifPriorityTorchOFF - Notification Priority when the LED is off. Default is "-1". Versions before 2.0.3.41 including 1.x.x are hardcoded at "-2"
Important: Before changing any settings, be sure to kill ZTorch with a task manager. Otherwise the settings will not take effect and they will be overwritten when the app gets sent to the background.
If you mess up the settings ZTorch will force close on launch. Delete the XML file to restore defaults.
Strobe Light:
You can get some pretty cool stobbing effects by changing the "mask" and "max" settings.
If you set the "max" value to something like 200 with the mask set to 15 (0000-1111), when sliding the slidebar from 0 to 200, the actual brightness set will repeat 0-15 over and over.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Setting Brightness from other apps such as Tasker, using ZTorch's BroadcastReceiver
I still have to test if this works, but in theory it should. The ZTorchReceiver supports the actions below.
Code:
"derekziemba.ztorch.UPDATE_LEVEL"; //Service will check for extra Integer under the key "lvl" and set that brightness if it is valid.
"derekziemba.ztorch.WIDGET_TAP"; //Behave as if the widget was just tapped. MultiTap, TapGuard, and Wait apply.
"derekziemba.ztorch.STEP_UP"; //Increment Brightness by increment value
"derekziemba.ztorch.STEP_DOWN"; //Decrement Brightness by increment value
"derekziemba.ztorch.INCREASE"; //Increase Brightness by 1
"derekziemba.ztorch.DECREASE"; //Decrease Brightness by 1
"derekziemba.ztorch.ENABLE"; //Turn on torch at default level
"derekziemba.ztorch.DISABLE"; //Turn off torch
"derekziemba.ztorch.TOGGLE"; //Toggle the torch opposite its current state.
---------------------------------Internal---------------------------
"derekziemba.ztorch.UPDATE_FROM_MAIN"; //From main activity, prevents service from broadcasting UPDATE_FROM_SERVICE and cause an endless loop. Contains extra Integer under key "lvl"
"derekziemba.ztorch.UPDATE_FROM_SERVICE"; //Sent from the Service to Main, this one is Unregistered when Main is not visible. It is still sent by the service.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Important Note Regarding Brightness:
For default settings I have the max LED value set to 13 because I've experienced flicker. Values higher than 10 change the color of the slider to red and the widget and notification flame from yellow to fireball. Flicker occurs when your battery voltage is to low to support the current level of brightness.
To avoid LED flicker:
>3800+mV or ~50% is needed for Levels >=13.
> 3750mV or ~30% is needed for Levels > 9.
> 3600mV or ~10% is needed for Levels > 7.
I have used my app to work several hours in an attic at brightness 11. I used my phone because it's actually significantly brighter than every flashlight I own. That includes a flashlight with a 6V cell, a 3 LED headlamp, and a 4 battery AAA LED flashlight. My only light that beat it was my spotlight, but the spotlight's beam is too focused whereas the phone lights up everything.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Note: Android displays the build version as 1 higher than the file name. So Android will show version 2.0.3.41 as 2.0.3.42. This is caused by some Gradle Build Config bug.
I use the torch a lot so I just downloaded this and I'll definitely let you know how it goes. Thanks!
Verizon S4
Liquid Smooth 4.4
Sprint S4
Negalite 4.4
Great app. Been using it for a few days with no issues. Love the incremental increases/decreases.
Anyway to get this to stay in the notification drop down?
Sent from my SCH-I545 using Tapatalk 2
rahilkalim said:
Great app. Been using it for a few days with no issues. Love the incremental increases/decreases.
Anyway to get this to stay in the notification drop down?
Sent from my SCH-I545 using Tapatalk 2
Click to expand...
Click to collapse
I might be able to implement that as a setting quick when I get home. And maybe add an option to make it half height too if it's going to be persistent.
DerekZ10 said:
I might be able to implement that as a setting quick when I get home. And maybe add an option to make it half height too if it's going to be persistent.
Click to expand...
Click to collapse
That would be great. Thanks.
Sent from my SCH-I545 using Tapatalk 2
rahilkalim said:
That would be great. Thanks.
Sent from my SCH-I545 using Tapatalk 2
Click to expand...
Click to collapse
Just updated it. Here's what's new:
Settings Activity has had a makeover. The question mark on the side will explain what the settings do. The image on the left shows what it looks like if the Persistent Notification and the Minimizing Notification toggles are enabled. The right shows what it looks like with the Minimizing Notification toggle off. Notice that when the Minimizing Notification toggle is disabled, zTorch's icon is in the notification bar.
Here is what zTorch looks like in the notification drop down with minimization enabled. The left screenshot is with zTorch minimized. In this state the icon is not in the notification bar. The screenshot ion the right shows the notification expanded with the minimize option enabled, In this state the icon will show up in the notification bar.
Disabling Notification minimization but keeping Persistent notification enabled will cause the notification to appear like the left and middle screenshots. When the Torch is off, only an Activate LED button is present. If there are a large number of other notification, the notification will shrink up. With the Torch on more buttons become available as seen in the middle screenshot. The rightmost screenshot is the notification with both the persistent notification and notification minimization disabled.
Note: This version 1.2.0 has some rough edges. I'll polish it when I have more time. In the future the Settings activity will also be changed to an actual Android Settings layout instead of a generic layout.
EDIT: Version 1.2.1 rounds out those edges.
Now that school is out, I'll be updating and posting the source code on github soon
DerekZ10 said:
Now that school is out, I'll be updating and posting the source code on github soon
Click to expand...
Click to collapse
Great job, works great!
This looks great. Do you have any plans to update this for nc5 4.4.2 compatibility?
Sent from my SCH-I545 using Tapatalk
klabit87 said:
This looks great. Do you have any plans to update this for nc5 4.4.2 compatibility?
Sent from my SCH-I545 using Tapatalk
Click to expand...
Click to collapse
This is why I wanna get the source code up. So others can compile it for their versions. I'm running Android 4.2.2 Eclipse 2.0 Rom. It's all customized and set up the way I like, and it's been very reliable. I'm not sure when I will get around to upgrading. Every rom I have tried as a replacement has had problems.
I haven't got around to posting the source code because there was suddenly some issues with the build? I opened the project the other day and was told I needed to upgrade things, I did and now every object and include directive is underlined in red. I looked at it for about a minute before deciding I'll figure it out some other day. Haven't got around to it since.
Oh ok. I was just wondering. Looking forward to the source so we can have it work for updated android versions someday.
Thanks.
Sent from my SCH-I545 using Tapatalk
klabit87 said:
Oh ok. I was just wondering. Looking forward to the source so we can have it work for updated android versions someday.
Thanks.
Sent from my SCH-I545 using Tapatalk
Click to expand...
Click to collapse
Here's the Source Code Everyone, Good Luck! Everything for the project should be on GitHub including external libraries and the .psd files for the icons.
https://github.com/DerekZiemba/zTorch
I haven't been able to build this or other projects since upgrading the SDK and the Eclipse ADT. I'm not getting any errors, I just get "export build failed." Not sure what to do, maybe reinstall everything. Hopefully someone here can get it working. I just really don't have enough time. In fact the whole project was born out of procrastinating a huge report I didn't want to do for school.
I have everything working again and the source code should build the most stable recent version. The 1.3 beta version is on my dropbox now. This version is a work in progress and the new TorchPlayer feature is not in a working state, but everything else works as usual.
I'm releasing this build before this new feature is working so people with newer versions of android can use the apps pre-existing features.
Here is basically what TorchPlayer is and how it will effect the app in future versions:
Once working properly it will be used to define increment steps for things such as rapid-tap and consecutive-tap (currently double-tap). The time element of these steps will define the max time the LED will stay lit before (likely) dropping down a step. It will be a way to prevent the LED being lit in your pocket all day and limiting the max LED brightness to a defined time.
TorchPlayer will eventually allow you to name and save sequences and have a repeat mode so you can use it as a strobe light. I'm not sure yet how fast the LED can be switched on and off. I might also look into having the sequence controlled by Morse code using dots and dashes.
For this to work I have to figure out, basically, multi-threading(handlers, runnables, threads) and a few other things such as Gson or SQLite.
NOTE: Installing this version messed up my widget. If it happens to you just delete it and re add it to fix.
Shown below is version 1.3 beta 4. I've found that I can strobe the led light ridiculously fast. I haven't encountered the limit yet at even the 5 millisecond intervals. At 5millis the LED is flashing so fast that it is almost becoming steady. With this it may be possible to set custom "LightTones" for certain things like you do with ring tones.
EDIT:
Beta 5 added ability to duplicate several values to save on typing as seen below: Also note, the parenthesis and spaces don't actually matter and are only there to make it easier on me to read. The input is sanitized using: String scheme = behavior.replaceAll("[^0-9/sm,.*&]+",""); So only numbers, the letters s and m, and the symbols / , . * & matter. If a brightness value is out of range that command is ignored.
Here is a video of what the above TorchPlayer string yields.
https://www.youtube.com/watch?v=c1lwTHZwr-M&feature=youtu.be
DerekZ10 said:
I have everything working again and the source code should build the most stable recent version. The 1.3 beta version is on my dropbox now. This version is a work in progress and the new TorchPlayer feature is not in a working state, but everything else works as usual.
I'm releasing this build before this new feature is working so people with newer versions of android can use the apps pre-existing features.
Here is basically what TorchPlayer is and how it will effect the app in future versions:
Once working properly it will be used to define increment steps for things such as rapid-tap and consecutive-tap (currently double-tap). The time element of these steps will define the max time the LED will stay lit before (likely) dropping down a step. It will be a way to prevent the LED being lit in your pocket all day and limiting the max LED brightness to a defined time.
TorchPlayer will eventually allow you to name and save sequences and have a repeat mode so you can use it as a strobe light. I'm not sure yet how fast the LED can be switched on and off. I might also look into having the sequence controlled by Morse code using dots and dashes.
For this to work I have to figure out, basically, multi-threading(handlers, runnables, threads) and a few other things such as Gson or SQLite.
NOTE: Installing this version messed up my widget. If it happens to you just delete it and re add it to fix.
Click to expand...
Click to collapse
For some reason the toggle doesn't show in my drop down now, any ideas?
shindiggity said:
For some reason the toggle doesn't show in my drop down now, any ideas?
Click to expand...
Click to collapse
Just confirmed it is a bug. To get the notification to show you need to switch the torch on once. It'll stay in the dropdown after.
I'll try to get a new build together soon. I learned a few things about Android the other day that made me realize my code was overly complicated and difficult to work with, much more so than it ever needed to be. So I actually started a total rewrite since that version that I want to get perfect.
The new version is a different app all together, the system and launcher will see it as zTorch-L. The L stands for it really being the "Lite" version, in app it will refer to it self as zTorch-Lightning. I decided that the TorchPlayer feature went against the whole purpose of making my own app in the first place. I created it to be fast, simple, no-bs or bugs, do one thing and do it well. What I wanted out of TorchPlayer would cause the app to loose focus of its goal, so I started this new version that would be just that.
Because I want it to be totally finished before releasing, I'm not going to post a link to it here. The code wouldn't even compile if I tried. But if you really rely on the notification being in the dropdown PM me. I have an alpha version I compiled before going to far in to rewriting the code. Everything works great AFTER some tweaking first.
Initially it is inoperable unless, starting from the root directory, you navigate to the following file:
Code:
/data/data/derekziemba.ztorchL/shared_prefs/derekziemba.ztorchL_preferences.xml
Open it, delete what ever is in it, then paste the below text :
Code:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="flash_current_value" value="0" />
<int name="tap_time" value="900" />
<int name="brightness_increment_steps" value="3" />
<int name="default_value" value="8" />
<int name="flash_limit_value" value="13" />
<boolean name="rapid_tap" value="true" />
<boolean name="persistent_notif" value="true" />
<boolean name="mini_notif" value="true" />
</map>
I sent you a PM, be happy too.
DerekZ10 said:
Just confirmed it is a bug. To get the notification to show you need to switch the torch on once. It'll stay in the dropdown after.
I'll try to get a new build together soon. I learned a few things about Android the other day that made me realize my code was overly complicated and difficult to work with, much more so than it ever needed to be. So I actually started a total rewrite since that version that I want to get perfect.
The new version is a different app all together, the system and launcher will see it as zTorch-L. The L stands for it really being the "Lite" version, in app it will refer to it self as zTorch-Lightning. I decided that the TorchPlayer feature went against the whole purpose of making my own app in the first place. I created it to be fast, simple, no-bs or bugs, do one thing and do it well. What I wanted out of TorchPlayer would cause the app to loose focus of its goal, so I started this new version that would be just that.
Because I want it to be totally finished before releasing, I'm not going to post a link to it here. The code wouldn't even compile if I tried. But if you really rely on the notification being in the dropdown PM me. I have an alpha version I compiled before going to far in to rewriting the code. Everything works great AFTER some tweaking first.
Initially it is inoperable unless, starting from the root directory, you navigate to the following file:
Code:
/data/data/derekziemba.ztorchL/shared_prefs/derekziemba.ztorchL_preferences.xml
Open it, delete what ever is in it, then paste the below text :
Code:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="flash_current_value" value="0" />
<int name="tap_time" value="900" />
<int name="brightness_increment_steps" value="3" />
<int name="default_value" value="8" />
<int name="flash_limit_value" value="13" />
<boolean name="rapid_tap" value="true" />
<boolean name="persistent_notif" value="true" />
<boolean name="mini_notif" value="true" />
</map>
Click to expand...
Click to collapse
shindiggity said:
I sent you a PM, be happy too.
Click to expand...
Click to collapse
So you guys don't have to keep using that version if you don't want to, try the zTorch-Lightning_v1.Alpha2 . There's a lot of stuff to do yet, but all the basics are working.
You'll notice the notification is way more responsive and that it no longer does that thing "refresh flash" when switching to different notification styles. It responds instantly to setting changes now too.
When tapping the 1x1 incremental widget, the LED is now set to turn on before the system broadcast and before the on screen widget lights up instead of the other way around.
http://db.orangedox.com/FBzt4wNNfVu1xIMc0W/zTorch-Lightning_v1.Alpha2.apk
This is just what i have been looking for!! So what kind of licensing is your code on git under?
Adjustable flash brightness is just what i want to look adding to my Camera app. I need something lower intensity than the stock.
Unfortunately, I am unable to test this app as my rooted devices don't have flash.
hotspot_volcano said:
This is just what i have been looking for!! So what kind of licensing is your code on git under?
Adjustable flash brightness is just what i want to look adding to my Camera app. I need something lower intensity than the stock.
Unfortunately, I am unable to test this app as my rooted devices don't have flash.
Click to expand...
Click to collapse
Free to use as long as you don't repackage it as is but with ads or put a price on the app. However if you are creating your own app and just want to use the flashlight feature, you can use the below code however you want. I think the git code is way out of date, I worked on it a bit a while ago and I don't think I comited it. I've gotten busy and haven't had a chance to work on it in months.
Here is the code for directly changing the brightness. Free to Use however you wish.
Here is the Shell Class. The Static Methods create and maintain the superuser shell. Therefor a command can be executed app wide on a single shell instead of creating multiple Shell instances.
Code:
package derekziemba.misc;
import java.io.*;
public class Shell {
private static Shell rootShell = null;
private final Process proc;
private final OutputStreamWriter writer;
private Shell() throws IOException {//Open with Root Privileges
this.proc = new ProcessBuilder("su").redirectErrorStream(true).start();
this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
}
private void cmd(String command) {
try{ writer.write(command+'\n'); writer.flush();}
catch(IOException e) { }
}
public void close() {
try {
if (writer != null) { writer.close();
if(proc != null) { proc.destroy(); }
}
} catch (IOException ignore) {}
}
public static void exec(String command) { Shell.get().cmd(command); }
public static Shell get() {
if (rootShell == null) {
while (rootShell == null) {
try { rootShell = new Shell(); }
catch (IOException e) { }
}
}
return rootShell;
}
}
}
Here is what is used for setting the flash brightness. I stripped out all the app logic. SetLevelCovertly is the actual method used for setting the brightness. It is what the TorchPlayer uses to directly change the brightness in just milliseconds. The stripped away normal SetLevel method records the brightness, triggers the broadcasts, sets the widgets, and fires the notification. There is no way of getting the current flashlevel brightness since my Shell implementation is just for blasting commands at the terminal. Anything more will slow it down.
The listOfFlashFiles is a bunch of different files different phones may use. I've only ever tested the samsung file.
Code:
import java.io.File;
import derekziemba.misc.Shell;
public class Torch
{
private static String FLASH_FILE = null;
private static final String[] listOfFlashFiles = {
"/sys/class/camera/flash/rear_flash",
"/sys/class/camera/rear/rear_flash",
"/sys/class/leds/flashlight/brightness",
"/sys/devices/platform/flashlight.0/leds/flashlight/brightness",
"/sys/class/leds/spotlight/brightness",
"/sys/class/leds/torch-flash/flash_light"
};
/**
* Bypasses all checks and settings and just sets the value. The app will not know what the level is because it is not recorded.
* Will not trigger broadcast, widget views, notification
*/
public static void setLevelCovertly(int value) { Shell.exec("echo " + value + " > "+ getSysFsFile()); }
public static String getSysFsFile() {
if (FLASH_FILE != null) return FLASH_FILE;
for (String filePath : listOfFlashFiles) {
File flashFile = new File(filePath);
if (flashFile.exists()) { FLASH_FILE = filePath; }
}
return FLASH_FILE;
}

Using the Master/Detail template in ViewPager Fragments (download link)

Working code: https://github.com/lukeallison/ViewPagerMasterDetail
Android Master/Detail Flow template: http://developer.android.com/tools/projects/templates.html#master-detail-activity
Description: Using the Master/Detail Flow template available in Android Studio, my application utilizes a ViewPager to manage three Parent fragments. The third fragment is a Master (list), which has a Child (detail) fragment.
Issues:
1. When fragment_item_list is first inflated the App Bar pushes the last item of the list below the bounds of the screen. This issue is no longer present after rotating the device. Simply adding padding to the bottom of the screen will not fix the issue as it will leave an unwanted space at the bottom of the screen after rotating. Numerous SO threads have failed to address this issue. - Fixed
2. Requires android:configChanges="orientation|keyboardHidden|screenSize" added to the manifest in order for the Child (detail) fragment to inflate the correct layout when rotated. I'd like to not have to enforce this. PLEASE help fix this bug.
3. Uses deprecated setOnPageChangeListener and onAttach(Activity)
4. Upgrading the dependencies to 23.2.0 results in the ItemListFragment failing to inflate the correct Fragment when rotated so I can't update the libraries in the application
5. The code is probably more cumbersome than necessary
Please help me fix these bugs so we have a template that myself and others can use.
Just a cheeky bump.

How to use Huawei Ads Kit with Flutter

Hello everyone, In this article, We will bring Huawei Ads to your Flutter app!
What is the Ads Kit ?
Ads kit is used to obtain revenues. HUAWEI Ads Publisher Service utilizes Huawei’s vast user base and extensive data capabilities to deliver targeted, high quality ads to users.
Huawei Mobile Services Integration
Firstly, If you haven’t integrated Huawei Mobile Services to your app yet, please do it "https://medium.com/huawei-developers/android-integrating-your-apps-with-huawei-hms-core-1f1e2a090e98" here. After integration, you are ready to write some Dart code!
Flutter Integration
Get the latest version number from "https://pub.dev/packages/huawei_ads" official pub.dev package and add dependency to your pubspec.yaml;
Code:
dependencies:
huawei_ads: # Latest Version Number
Or download the package from "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Library-V1/flutter-sdk-download-0000001050196675-V1" Huawei Developer Website, extract the archive and add dependency as path;
Code:
dependencies:
huawei_ads:
path: # The path that you extracted archive to
huawei_ads:path: # The path that you extracted archive to
Usage
There are number of display options for Huawei Ads;
Banner Ads : Banner ads are rectangular images that occupy a spot at the top, middle, or bottom within an app’s layout. Banner ads refresh automatically at intervals. When a user taps a banner ad, the user is redirected to the advertiser’s page in most cases. "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Guides/banner-ads-0000001050436805-V1" for details
Interstitial ads : Interstitial ads are full-screen ads that cover the interface of an app. Such ads are displayed when a user starts, pauses, or exits an app, without disrupting the user’s experience. "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Guides/interstitial-ads-0000001050196804-V1" for details
Rewarded Ads : Rewarded ads are full-screen video ads that users opt to view in exchange for in-app rewards. "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Guides/rewarded-ads-0000001050315988-V1" for details
Splash ads : Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed. "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Guides/splash-ads-0000001050439035-V1" for details
Native Ads : Native ads are typical ad materials that are displayed on the customized interface of an app so that they can fit seamlessly into the surrounding content in the app. "https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Guides/native-ads-0000001050198817-V1" for details
Banner Ads
Banner Ad’s lifecycle can be managed from BannerAd object. Create it with your Ad Slot ID.
Code:
BannerAd bannerAd = BannerAd(
adSlotId: "testw6vs28auh3", // This is test slot id for banner ad
size: BannerAdSize.s320x50, // Banner size
adParam: AdParam(), // Special request options
bannerRefreshTime: 60, // Refresh time in seconds
listener: (AdEvent event, {int errorCode}) { // Event listener
print("Banner Ad event : $event");
},
);
Call loadAd() and show() functions sequentially to display the Banner Ad.
Code:
bannerAd.loadAd(); // Loading ad
bannerAd.show(); // Showing ad at the bottom of the page
r/HMSCore - How to use Huawei Ads Kit with Flutter
Banner Ad Page from Example Project
And finally don’t forget to destroy banner view at the desired point.
Code:
bannerAd.destroy(); // Destroying ad view
Interstitial Ads
You can display an Interstitial Ad with InterstitialAd object. Functions are same as Banner’s. Just call loadAd() and show() sequentially.
Code:
InterstitialAd interstitialAd = InterstitialAd(
adSlotId: "teste9ih9j0rc3", // This is test slot id for interstitial ad
adParam: AdParam(), // Special request options
listener: (AdEvent event, {int errorCode}) { // Event listener
print("Interstitial Ad event : $event");
},
);
interstitialAd.loadAd(); // Loading ad
interstitialAd.show(); // Showing ad full screen
... interstitialAd.destroy(); // Destroying full screen activity programatically
r/HMSCore - How to use Huawei Ads Kit with Flutter
Interstitial Ad Example
Reward Ads
Reward Ad flow can be started with a RewardAd object.
As you can see; if a user completes the reward process, you can use Reward object in listener callback.
Code:
RewardAd rewardAd = RewardAd(
listener: (RewardAdEvent event, {Reward reward, int errorCode}) { // Event listener for reward ad
print("RewardAd event : $event");
if (event == RewardAdEvent.rewarded) {
print('Received reward : ${jsonEncode(reward.toJson())}');
}
}
);
rewardAd.loadAd( // Loading ad
adSlotId: "testx9dtjwj8hp", // This is test slot id for reward ad
adParam: AdParam(), // Special request options
);
rewardAd.show(); // Showing ad full screen
... rewardAd.destroy(); // Destroying full screen activity programatically
r/HMSCore - How to use Huawei Ads Kit with Flutter
Collecting Reward Ad Events, Example Project
Splash Ads
With Splash Ad you can show non-skippable, highly customizable full screen ad from anywhere of your app.
Code:
SplashAd splashAd = SplashAd(
adType: SplashAdType.above, // Splash ad type
loadListener: (SplashAdLoadEvent event, {int errorCode}) { // loading events listened here
print("Splash Ad Load event : $event");
... // Handle how your app behave when splash ad started and ended
},
displayListener: (SplashAdDisplayEvent event) { // display events listened here
print("Splash Ad Display Event : $event");
},
);
splashAd.loadAd( // Loads and shows the splash ad
adSlotId: "testq6zq98hecj", // This is test slot id for splash ad
orientation: SplashAdOrientation.portrait, // Orientation
adParam: AdParam(), // Special request options
);
... splashAd.destroy(); // Destroying full screen activity programatically
Native Ads
Native Ads can be placed anywhere in your app as widget. Events can be listened with NativeAdController object and the widget can be customized with type and styles parameters.
Code:
NativeAd(
adSlotId: "testb65czjivt9", // small native template test id
controller: NativeAdController(), // native ad configuration and parameters
type: NativeAdType.small, // native ad type
styles: NativeStyles(), // native ad style
)
r/HMSCore - How to use Huawei Ads Kit with Flutter
Native Ads in list, Example Project
Huawei Ads Publisher Service
In this article we used test identifiers for ads. But; You need a Huawei Developer Account with Merchant Service enabled, for getting real Ad Slot ID. With these Ad Slot ID’s, Huawei can serve ads through your view and collect your revenue.
Further information, please take a look at these official docs;
"https://developer.huawei.com/consumer/en/doc/distribution/monetize/0603" App Integration Process
"https://developer.huawei.com/consumer/en/doc/distribution/monetize/Monetizeaddappandunit" Add App and Unit
Conclusion
Congratulations! It is really easy to display Huawei Ads in a Flutter app. If you run into a problem, write a comment. I would love to help!
Reference
"https://github.com/HMS-Core/hms-flutter-plugin/tree/master/flutter-hms-ads" Example Project - GitHub
"https://developer.huawei.com/consumer/en/hms/huawei-adskit/" Huawei Ads Kit
How much we can earn from ads kit. Is there any monetary system ?

Several Easy Steps to Integrate the Fundamental Capability SDK of Video Editor Kit

The launch of HMS Core Video Editor Kit 6.2.0 has brought two notable highlights: various AI-empowered capabilities and flexible integration methods. One method is to integrate the fundamental capability SDK, which is described below.
Preparations​For details, please check the official document.
Code Development​Configuring a Video Editing Project
1. Set the authentication information for your app through an API key or access token.
Use the setAccessToken method to set an access token when the app is started. The access token needs to be set only once.
Code:
MediaApplication.getInstance().setAccessToken("your access token");
Use the setApiKey method to set an API key when the app is started. The API key needs to be set only once.
Code:
MediaApplication.getInstance().setApiKey("your ApiKey");
2. Set a License ID.
This ID is used to manage your usage quotas, so ensure that the ID is unique.
Code:
MediaApplication.getInstance().setLicenseId("License ID");
3. Initialize the running environment for HuaweiVideoEditor.
When creating a video editing project, first create a HuaweiVideoEditor object and initialize its running environment. When exiting a video editing project, release the HuaweiVideoEditor object.
Create a HuaweiVideoEditor object.
Code:
HuaweiVideoEditor editor = HuaweiVideoEditor.create(getApplicationContext());
Specify the position for the preview area.
This area renders video images, which is implemented by creating SurfaceView in the fundamental capability SDK. Ensure that the preview area position on your app is specified before creating this area.
Code:
<LinearLayout
android:id="@+id/video_content_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/video_edit_main_bg_color"
android:gravity="center"
android:orientation="vertical" />
// Specify the preview area position.
LinearLayout mSdkPreviewContainer = view.findViewById(R.id.video_content_layout);
// Set the layout of the preview area.
editor.setDisplay(mSdkPreviewContainer);
Initialize the running environment. If the license verification fails, LicenseException will be thrown.
After the HuaweiVideoEditor object is created, it has not occupied any system resource. You need to manually set the time for initializing the running environment of the object. Then, necessary threads and timers will be created in the fundamental capability SDK.
Code:
try {
editor.initEnvironment();
} catch (LicenseException error) {
SmartLog.e(TAG, "initEnvironment failed: " + error.getErrorMsg());
finish();
return;
}
4. Add a video or image.
Create a video lane and add a video or image to the lane using the file path.
Code:
// Obtain the HVETimeLine object.
HVETimeLine timeline = editor.getTimeLine();
// Create a video lane.
HVEVideoLane videoLane = timeline.appendVideoLane();
// Add a video to the end of the video lane.
HVEVideoAsset videoAsset = videoLane.appendVideoAsset("test.mp4");
// Add an image to the end of the video lane.
HVEImageAsset imageAsset = videoLane.appendImageAsset("test.jpg");
5. Add audio.
Create an audio lane and add audio to the lane using the file path.
Code:
// Create an audio lane.
HVEAudioLane audioLane = timeline.appendAudioLane();
// Add an audio asset to the end of the audio lane.
HVEAudioAsset audioAsset = audioLane.appendAudioAsset("test.mp3");
6. Add a sticker and text.
Create a sticker lane and add a sticker and text to the lane. A sticker needs to be added using its file path, while the text needs to be added by specifying its content.
Code:
// Create a sticker lane.
HVEStickerLane stickerLane = timeline.appendStickerLane();
// Add a sticker to the end of the lane.
HVEStickerAsset stickerAsset = stickerLane.appendStickerAsset("test.png");
// Add text to the end of the lane.
HVEWordAsset wordAsset = stickerLane.appendWord("Input text",0,3000);
7. Add a special effect.
Special effects are classified into the external special effect and embedded special effect.
Add an external special effect to an effect lane. This special effect can be applied to multiple assets, and its duration can be adjusted.
Code:
// Create an effect lane.
HVEEffectLane effectLane = timeline.appendEffectLane();
// Create a color adjustment effect with a duration of 3000 ms. Add it to the 0 ms playback position of the lane.
HVEEffect effect = effectLane.appendEffect(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), 0, 3000);
Add an embedded special effect to an asset. Such a special effect can be applied to a single asset. The special effect's duration is the same as that of the asset and cannot be adjusted.
Code:
// Create an embedded special effect of color adjustment.
HVEEffect effect = videoAsset.appendEffectUniqueOfType(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), ADJUST);
8. Play a timeline.
To play a timeline, specify its start time and end time. The timeline will play from its start time to end time at a fixed frame rate, and the image and sound in the preview will play simultaneously. You can obtain the playback progress, playback pause, payback completion, and playback failure via the registered callback.
Code:
// Register the playback progress callback.
editor.setPlayCallback(callback);
// Play the complete timeline.
editor.playTimeLine(timeline.getStartTime(), timeline.getEndTime());
9. Export a video.
After the editing is complete, export a new video using the assets in the timeline via the export API. Set the export callback to listen to the export progress, export completion, or export failure, and specify the frame rate, resolution, and path for the video to be exported.
Code:
// Path for the video to be exported.
String outputPath =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + Constant.LOCAL_VIDEO_SAVE_PATH
+ File.separator + VideoExportActivity.getTime() + ".mp4";
// Resolution for the video to be exported.
HVEVideoProperty videoProperty = new HVEVideoProperty(1920, 1080);
// Export the video.
HVEExportManager.exportVideo(targetEditor, callback, videoProperty, outputPath);
Managing Materials
After allocating materials, use APIs provided in the on-cloud material management module to query and download a specified material. For details, please refer to the description in the official document.
Integrating an AI-Empowered Capability
The fundamental capability SDK of Video Editor Kit provides multiple AI-empowered capabilities including AI filter, track person, moving picture, and AI color, for integration into your app. For more details, please refer to the instruction in this document.
AI Filter
Lets users flexibly customize and apply a filter to their imported videos and images.
Code:
// Create an AI algorithm engine for AI filter.
HVEExclusiveFilter filterEngine = new HVEExclusiveFilter();
// Initialize the engine.
mFilterEngine.initExclusiveFilterEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Create an AI filter of the extract type from an image, by specifying the image bitmap and filter name.
// The filter ID is returned. Using the ID, you can query all information about the filter in the database.
String effectId = mFilterEngine.createExclusiveEffect(bitmap, "AI filter 01");
// Add the filter for the first 3000 ms segment of the effect lane.
effectLane.appendEffect(new HVEEffect.Options(
HVEEffect.CUSTOM_FILTER + mSelectName, effectId, ""), 0, 3000);
Color Hair
Changes the hair color of one or more persons detected in the imported image, in just a tap. The color strength is adjustable.
Code:
// Initialize the AI algorithm for the color hair effect.
asset.initHairDyeingEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Add the color hair effect by specifying a color and the default strength.
asset.addHairDyeingEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
}, colorPath, defaultStrength);
// Remove the color hair effect.
asset.removeHairDyeingEffect();
Moving Picture
Animates one or more persons in the imported image, so that they smile, nod, or more.
Code:
// Add the moving picture effect.
asset.addFaceReenactAIEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
});
// Remove the moving picture effect.
asset.removeFaceReenactAIEffect();
This article presents just a few features of Video Editor Kit. For more, check here.
To learn more, please visit:
>> HUAWEI Developers official website
>> Development Guide
>> Reddit to join developer discussions
>> GitHub to download the sample code
>> Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.

Categories

Resources