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;
}
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 ?
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.
PreparationsFor details, please check the official document.
Code DevelopmentConfiguring 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.