Can't install APK |No content provider found for permission revoke: - Android Q&A, Help & Troubleshooting

I can't seem to install 'Bladeslinger' (from the humble mobile bundle)
on my Samsung galaxy s2 skyrocket.
I have 1gb of ram, and 450mb of free space on the device and 4gb of free space on the internal sd card.
and I re-download the game 3 times using the humble bundle app, and the web page, but every time I try to install it,
it says "could not be installed". or something like that.
here is the log cat info:
E/NativeDaemonConnector.ResponseQueue( 495): Timeout waiting for response
E/VoldConnector( 495): timed-out waiting for response to 473 asec create smdl2tmp2 344 fat 7e3849364ba675a4fcd859afb4e47bc2 10015 1
E/PackageHelper(13624): Failed to create secure container smdl2tmp2
E/DefContainer(13624): Failed to create container smdl2tmp2
W/ActivityManager( 495): No content provider found for permission revoke: file:///storage/sdcard0/Download/humblebundle/Bladeslinger_HIB_2013-03-22.apk
D/dalvikvm( 495): WAIT_FOR_CONCURRENT_GC blocked 0ms
D/STATUSBAR-NetworkController( 662): refreshSignalCluster: data=0 bt=false
D/STATUSBAR-SignalClusterView( 662): animating mobile roaming failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): frameAnimation failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): animating mobile roaming failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): frameAnimation failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): animating mobile roaming failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): frameAnimation failed, reason [null]
D/dalvikvm( 495): GC_EXPLICIT freed 954K, 13% free 43304K/49287K, paused 18ms+19ms, total 265ms
D/InstallAppProgress(13553): Installation error code: -18
D/STATUSBAR-NetworkController( 662): refreshSignalCluster: data=0 bt=false
D/STATUSBAR-SignalClusterView( 662): animating mobile roaming failed, reason [null]
D/STATUSBAR-SignalClusterView( 662): frameAnimation failed, reason [null]
I emailed their support about two weeks ago, and got no reply,
I also tried to check the support page, And I had no luck there either.
other things i've tried:
+install from ADB
(It said: /sbin/sh: /system/bin/pm: Permission denied)
+install from ADB to SD card
(samething)
+Install APK from file manager
(Error says "...was not installed")
Any Ideas?

Is that a system app from other device if yes then you can't as system app uses some of there own permissions which are not available in general android ones
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!

It's not a system app, it's just a game,
And it was a downloaded apk,
Not transferred from another device.
Dose that help?

Why not download it from play store
If its not there then your device does not support it
If you say it's paid no help from me I oppose wares
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!

apk was not pirated -
you can take a look here
Code:
https://www.humblebundle.com/
It was dowloaded through app that humble bundle provides AFAIK
and i think its also support SGS2
looks like that folder where apk is stored doesnt have write premission

Sorry for the confusion,
I did buy it,
But not from the play store,
I bought it from the humble indie bundle,
It's a charity sale thing, it's only like $3 on the store,
So I could buy it again, but I'd rather not spend the extra money.

Here are some tips I think would help. From my experience with "not been able to install APK" first thing I do is to get some sort of file explorer. This enables you to locate and install files from your sd card with ease. Now, there are varieties of file explorers in the market, try and grab one.
Now there are three means of getting the file explorer installed on your device. First, is Bluetooth. Place the APK of the explorer in another device that can transfer. Now note, phones like Nokia will not do the trick, see if you can lay your hands on a sony ericsson. That's why I love Sony, they are not selfish.
Secondly, download directly from the market
Thridly, use your device pc suit, with that you can place the explorer apk in your pc then connect your device and install the APK using the suit.
Something else you might try is using Norton utilities. Its a multi level file manager. With it you can install apk files that are placed on your memory card. Good luck.
Sent from my Sony Xperia Ray Smartphone.

Use es file explorer it comes with a apk installer which is different from stock give it a try
Sent from my GT-S5302 using Tapatalk 2
Hit Thanx Button if i helped you!

I have also tried this, I downloaded the apk from the humble bundle, and copied it to my phone, I tried Samsungs file manager, and es file manager, both were unable to install it.
richluv2003 said:
Here are some tips I think would help. From my experience with "not been able to install APK" first thing I do is to get some sort of file explorer. This enables you to locate and install files from your sd card with ease. Now, there are varieties of file explorers in the market, try and grab one.
Now there are three means of getting the file explorer installed on your device. First, is Bluetooth. Place the APK of the explorer in another device that can transfer. Now note, phones like Nokia will not do the trick, see if you can lay your hands on a don't ericsson. That's why I love don't.
Secondly, download directly from the market
Thridly, use your device pc suit, with that you can place the explorer apk in your pc then connect your device and install the APK using the suit.
Something else you might try is using Norton utilities. Its a multi level file manager. With it you can install apk files that are placed on your memory card. Good luck.
Sent from my Sony Xperia Ray Smartphone.
Click to expand...
Click to collapse

BOBdotEXE said:
I have also tried this, I downloaded the apk from the humble bundle, and copied it to my phone, I tried Samsungs file manager, and es file manager, both were unable to install it.
Click to expand...
Click to collapse
What phone do you have? A lot of the HumbleBundle games require ARM7 CPU. If you have an ARM6 phone, you will not be able to install it.
This is why I was unable to install World of Goo I bought from HumbleBundle on my Samsung Galaxy Ace.

Having the same issue on mine. I flashed paranoidandroid on my Sprint Note II last night and have been having this problem ever since. I've tried it with a few apps, like the humble bundle app and slidescreen launcher, and all of them have the same issue. When I go to install the install button is there, it just cannot be pressed, only the cancel button. I checked to ensure that Unknown Sources was checked, even toggled it a few times to make sure. Same with Verify Apps, no luck. I don't know if it's an issue with PA or it was happening before, because I haven't had to manually download an app in a long time.
For anyone interested, it's PA ver. 3.55 and Android ver 4.2.2 and I've tried installing through ES and stock browsers.

dougcgrubbs said:
Having the same issue on mine. I flashed paranoidandroid on my Sprint Note II last night and have been having this problem ever since. I've tried it with a few apps, like the humble bundle app and slidescreen launcher, and all of them have the same issue. When I go to install the install button is there, it just cannot be pressed, only the cancel button. I checked to ensure that Unknown Sources was checked, even toggled it a few times to make sure. Same with Verify Apps, no luck. I don't know if it's an issue with PA or it was happening before, because I haven't had to manually download an app in a long time.
For anyone interested, it's PA ver. 3.55 and Android ver 4.2.2 and I've tried installing through ES and stock browsers.
Click to expand...
Click to collapse
They're multi window apps right? I guess it's pandroid issue
Sent from my GT-S5302 using Tapatalk 2

Hi there.. little late but just wanted to post for reference.
BOBdotEXE said:
E/NativeDaemonConnector.ResponseQueue( 495): Timeout waiting for response
E/VoldConnector( 495): timed-out waiting for response to 473 asec create smdl2tmp2 344 fat 7e3849364ba675a4fcd859afb4e47bc2 10015 1
E/PackageHelper(13624): Failed to create secure container smdl2tmp2
E/DefContainer(13624): Failed to create container smdl2tmp2
W/ActivityManager( 495): No content provider found for permission revoke: file:///storage/sdcard0/Download/humblebundle/Bladeslinger_HIB_2013-03-22.apk
D/InstallAppProgress(13553): Installation error code: -18
Any Ideas?
Click to expand...
Click to collapse
The actual error is the timeout, the other message is just a warning. The given "Installation error code"s of InstallAppProgress can be found in android source f.e. @ frameworks/base/core/java/android/content/pm/PackageManager.java
Error -18 lists as
Code:
// ------ Errors related to sdcard
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* a secure container mount point couldn't be accessed on external media.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_CONTAINER_ERROR = -18;
And because we can, let's make this a real reference thread, behold, all INSTALL_* error codes :laugh: :
Code:
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} on success.
* @hide
*/
@SystemApi
public static final int INSTALL_SUCCEEDED = 1;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if the package is
* already installed.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_ALREADY_EXISTS = -1;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if the package archive
* file is invalid.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_INVALID_APK = -2;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if the URI passed in
* is invalid.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_INVALID_URI = -3;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if the package manager
* service found that the device didn't have enough storage space to install the app.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_INSUFFICIENT_STORAGE = -4;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if a
* package is already installed with the same name.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_DUPLICATE_PACKAGE = -5;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the requested shared user does not exist.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_NO_SHARED_USER = -6;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* a previously installed package of the same name has a different signature
* than the new package (and the old package's data was not removed).
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_UPDATE_INCOMPATIBLE = -7;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package is requested a shared user which is already installed on the
* device and does not have matching signature.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_SHARED_USER_INCOMPATIBLE = -8;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package uses a shared library that is not available.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_MISSING_SHARED_LIBRARY = -9;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package uses a shared library that is not available.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_REPLACE_COULDNT_DELETE = -10;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package failed while optimizing and validating its dex files,
* either because there was not enough storage or the validation failed.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_DEXOPT = -11;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package failed because the current SDK version is older than
* that required by the package.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_OLDER_SDK = -12;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package failed because it contains a content provider with the
* same authority as a provider already installed in the system.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_CONFLICTING_PROVIDER = -13;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package failed because the current SDK version is newer than
* that required by the package.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_NEWER_SDK = -14;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package failed because it has specified that it is a test-only
* package and the caller has not supplied the {@link #INSTALL_ALLOW_TEST}
* flag.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_TEST_ONLY = -15;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the package being installed contains native code, but none that is
* compatible with the device's CPU_ABI.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_CPU_ABI_INCOMPATIBLE = -16;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package uses a feature that is not available.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_MISSING_FEATURE = -17;
// ------ Errors related to sdcard
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* a secure container mount point couldn't be accessed on external media.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_CONTAINER_ERROR = -18;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package couldn't be installed in the specified install
* location.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_INVALID_INSTALL_LOCATION = -19;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package couldn't be installed in the specified install
* location because the media is not available.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_MEDIA_UNAVAILABLE = -20;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package couldn't be installed because the verification timed out.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_VERIFICATION_TIMEOUT = -21;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package couldn't be installed because the verification did not succeed.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_VERIFICATION_FAILURE = -22;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the package changed from what the calling program expected.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_PACKAGE_CHANGED = -23;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package is assigned a different UID than it previously held.
* @hide
*/
public static final int INSTALL_FAILED_UID_CHANGED = -24;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the new package has an older version code than the currently installed package.
* @hide
*/
public static final int INSTALL_FAILED_VERSION_DOWNGRADE = -25;
/**
* Installation return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)} if
* the package is from unknown sources but not trusted sources.
* @hide
*/
public static final int INSTALL_FAILED_UNKNOWN_SOURCES = -26;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser was given a path that is not a file, or does not end with the expected
* '.apk' extension.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_NOT_APK = -100;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser was unable to retrieve the AndroidManifest.xml file.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_BAD_MANIFEST = -101;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser encountered an unexpected exception.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION = -102;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser did not find any certificates in the .apk.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_NO_CERTIFICATES = -103;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser found inconsistent certificates on the files in the .apk.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES = -104;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser encountered a CertificateEncodingException in one of the
* files in the .apk.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING = -105;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser encountered a bad or missing package name in the manifest.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME = -106;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser encountered a bad shared user id name in the manifest.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID = -107;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser encountered some structural problem in the manifest.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_MANIFEST_MALFORMED = -108;
/**
* Installation parse return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the parser did not find any actionable tags (instrumentation or application)
* in the manifest.
* @hide
*/
@SystemApi
public static final int INSTALL_PARSE_FAILED_MANIFEST_EMPTY = -109;
/**
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the package because of system issues.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_INTERNAL_ERROR = -110;
/**
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the package because the user is restricted from installing
* apps.
* @hide
*/
public static final int INSTALL_FAILED_USER_RESTRICTED = -111;
/**
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the package because it is attempting to define a
* permission that is already defined by some existing package.
*
* <p>The package name of the app which has already defined the permission is passed to
* a {@link PackageInstallObserver}, if any, as the {@link #EXTRA_EXISTING_PACKAGE}
* string extra; and the name of the permission being redefined is passed in the
* {@link #EXTRA_EXISTING_PERMISSION} string extra.
* @hide
*/
public static final int INSTALL_FAILED_DUPLICATE_PERMISSION = -112;
/**
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the package because its packaged native code did not
* match any of the ABIs supported by the system.
*
* @hide
*/
public static final int INSTALL_FAILED_NO_MATCHING_ABIS = -113;
/**
* Internal return code for NativeLibraryHelper methods to indicate that the package
* being processed did not contain any native code. This is placed here only so that
* it can belong to the same value space as the other install failure codes.
*
* @hide
*/
public static final int NO_NATIVE_LIBRARIES = -114;
/** {@hide} */
public static final int INSTALL_FAILED_ABORTED = -115;
/**
* Used by themes
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the theme because aapt could not compile the app
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_THEME_AAPT_ERROR = -400;
/**
* Used by themes
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the theme because idmap failed
* apps.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_THEME_IDMAP_ERROR = -401;
/**
* Used by themes
* Installation failed return code: this is passed to the {@link IPackageInstallObserver} by
* {@link #installPackage(android.net.Uri, IPackageInstallObserver, int)}
* if the system failed to install the theme for an unknown reason
* apps.
* @hide
*/
@SystemApi
public static final int INSTALL_FAILED_THEME_UNKNOWN_ERROR = -402;

Related

OC Module project for Old s5p cpus

I'm Building Oc module for s5p and s3c cpus But I'm noop at C language.....
/*
* Author: Useby Ported this module from zdzihu's module
* Adapted from doixanh's X8Undervolt module
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include
#include
#include
#include
// defines
#define MODULE_NAME "Useby_oc"
#define MODULE_VER"001"
#define OFS_KALLSYMS_LOOKUP_NAME0xc0251e8c// kallsyms_lookup_name
//for future usage
static struct cpufreq_frequency_table freq_table_666_166MHz[] = {
{0, 1000000},
{1, (1000000)/2},
{2, (1000000)/3},
{3, (1000000)/4},
#ifdef SYSCLK_CHANGE
#ifdef USE_DVFS_AL1_LEVEL
{4, (1000000)/4},
{5, (1000000)/8},
{6, CPUFREQ_TABLE_END},
#else /* USE_DVFS_AL1_LEVEL */
{4, (1000000)/8},
{5, CPUFREQ_TABLE_END},
#endif /* USE_DVFS_AL1_LEVEL */
#else /* SYSCLK_CHANGE */
{4, CPUFREQ_TABLE_END},
#endif /* SYSCLK_CHANGE */
};
static struct cpufreq_policy *policy;
static struct cpufreq_frequency_table *freq_table;
// external variables / functions
typedef unsigned long (*kallsyms_lookup_name_type)(const char *name);
static kallsyms_lookup_name_type kallsyms_lookup_name_dx;
// init module
static int __init useby_oc_init(void)
{
printk(KERN_INFO MODULE_NAME ": module " MODULE_VER " loaded.\n");
// our 'GetProcAddress'
kallsyms_lookup_name_dx = (void*) OFS_KALLSYMS_LOOKUP_NAME;
// look for other offsets
freq_table = (void*) kallsyms_lookup_name_dx("s5p6442_freq_table");
policy = cpufreq_cpu_get(smp_processor_id());
freq_table = cpufreq_frequency_get_table(smp_processor_id());
freq_table[0].frequency = 1000000;
policy->cpuinfo.max_freq = 1000000;
policy->max = 1000000;
printk(KERN_INFO MODULE_NAME ": overclocking applied.\n");
return 0;
}
// exit module - will most likely not be called
static void __exit useby_oc_exit(void)
{
printk(KERN_INFO MODULE_NAME ": module unloaded\n");
}
module_init(useby_oc_init);
module_exit(useby_oc_exit);
MODULE_DESCRIPTION("Overclocking module for SG3");
MODULE_LICENSE("GPL");
When I first load Module Cpu master says It's 1000MHZ
But a Bit later It Says 667...again..
So Developers What about solving this quest? I think module is very useful!
From Source:
https://github.com/dharamg3/G3MOD/blob/master/Kernel/arch/arm/plat-s5p64xx/s5p6442-dvfs-perf.c
https://github.com/dharamg3/G3MOD/blob/master/Kernel/arch/arm/plat-s5p64xx/s5p6442-clock-perf.c
I know It's very old device but I want to Learn my module compiling from many phones

[Q] Sending GPS location via IOIO

Hi everyone
I'm fairly sure this is the right place to put this, but please correct me if I'm wrong.
I'm trying to create an app that take GPS coordinates from the inbuilt system and output it via an IOIO board (just a board that allows the phone to have digital and analogue output) so that it can be transmitted via a separate module to a receiver. The system will then be used to track a balloon.
I made some headway, I can send "Hello World" easily, but simply can't make the LocationManager work for me as using that just stops everything from working. My Java skills leave a lot to be desired, so I was hoping someone could check over my code and look for a fundamental mistake. The problem appears LocationUpdateHandler class, as relying on that to generate the 'stuff' variable simply halts the entire program.
It is based on two pieces of sample code that came with the IOIO board, but the GPS part is my own.
Code:
package ioio.examples.hello;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ToggleButton;
import ioio.lib.api.Uart;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
/**
* This is the main activity of the HelloIOIO example application.
*
* It displays a toggle button on the screen, which enables control of the
* on-board LED. This example shows a very simple usage of the IOIO, by using
* the {@link IOIOActivity} class. For a more advanced use case, see the
* HelloIOIOPower example.
*/
public class MainActivity extends IOIOActivity {
private ToggleButton button_;
private LocationManager locationManager;
String provider;
String stuff;
/**
* Called when the activity is first created. Here we normally initialize
* our GUI.
*/
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button_ = (ToggleButton) findViewById(R.id.button);
//Sets up the location manager and listener. I feel this section is the root of my problems
LocationListener locationListener = new LocationUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, new LocationUpdateHandler());
}
//Should, in theory, set the global variable 'stuff' to be the location of the phone stored as a string
public class LocationUpdateHandler implements LocationListener {
public void onLocationChanged(Location loc) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
stuff = Double.toString(lat) + "$" + Double.toString(lng) + "&";
}
[user=439709]@override[/user]
public void onProviderDisabled(String provider) {}
[user=439709]@override[/user]
public void onProviderEnabled(String provider) {}
[user=439709]@override[/user]
public void onStatusChanged(String provider, int status,
Bundle extras) {}
}
/**
* This is the thread on which all the IOIO activity happens. It will be run
* every time the application is resumed and aborted when it is paused. The
* method setup() will be called right after a connection with the IOIO has
* been established (which might happen several times!). Then, loop() will
* be called repetitively until the IOIO gets disconnected.
*/
class Looper extends BaseIOIOLooper {
/** The on-board LED. */
private DigitalOutput led_;
Uart uart;
OutputStream outGPS;
/**
* Called every time a connection with IOIO has been established.
* Typically used to open pins.
*
* [user=948141]@Throw[/user]s ConnectionLostException
* When IOIO connection is lost.
*
* [user=690402]@see[/user] ioio.lib.util.AbstractIOIOActivity.IOIOThread#setup()
*/
[user=439709]@override[/user]
public void setup() throws ConnectionLostException {
led_ = ioio_.openDigitalOutput(0, true);
uart = ioio_.openUart(3,4, 9600, Uart.Parity.NONE, Uart.StopBits.ONE);
outGPS = uart.getOutputStream();
}
public void loop() throws ConnectionLostException {
led_.write(!button_.isChecked());
byte[] GPSCoordinate = null;
//If I set stuff to "Hello World" here the IOIO board succesfully transmits hello world
try {
GPSCoordinate = stuff.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outGPS.write(GPSCoordinate);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
[user=439709]@override[/user]
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Thank you for your help,
Spanners.
and sorry about the code dump, but I think pretty much all of the code is important to understand the program.
Thanks.

Error compiling

Hi
Error static
Code:
@Deprecated public final class SmsManager {
private static SmsManager sInstance;
private android.telephony.SmsManager mSmsMgrProxy;
/** Get the default instance of the SmsManager
*
* @return the default instance of the SmsManager
* @deprecated Use android.telephony.SmsManager.
*/
@Deprecated
public static final SmsManager getDefault() {
if (sInstance == null) {
sInstance = new SmsManager();
to
Code:
@Deprecated public final class SmsManager {
private SmsManager sInstance;
private android.telephony.SmsManager mSmsMgrProxy;
/** Get the default instance of the SmsManager
*
* @return the default instance of the SmsManager
* @deprecated Use android.telephony.SmsManager.
*/
@Deprecated
public final SmsManager getDefault() {
if (sInstance == null) {
sInstance = new SmsManager();

Managing and Searching for Files in Drive Kit

Managing and Searching for Files
Use Case
File management is a core capability of HUAWEI Drive Kit. It enables users to conveniently manage and edit files in Drive , including creating, listing, copying, modifying, deleting, recycling, and searching for files.
Development Procedure
Step 1 Call the Drive.Builder.build API to create the Drive object.
Code:
private Drive buildDrive() {
Drive service = new Drive.Builder(CredentialManager.getInstance().getCredential(), context).build();
return service;
}
Step 2 Call the Files APIs.
NOTE:
Constants used in the sample code:
private static final int DIRECT_UPLOAD_MAX_SIZE = 20 * 1024 * 1024;
private static final int DIRECT_DOWNLOAD_MAX_SIZE = 20 * 1024 * 1024;
Call the Files.create API to create a folder.
Code:
/**
* Create a folder.
*/
private File createDirectory() {
File directory = null;
try {
Drive drive = buildDrive();
Map<String, String> appProperties = new HashMap<>();
appProperties.put("appProperties", "property");
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
String dirName = formatter.format(new Date());
File file = new File();
file.setFileName(dirName)
.setAppSettings(appProperties)
.setMimeType("application/vnd.huawei-apps.folder");
directory = drive.files().create(file).execute();
} catch (Exception e) {
Logger.e(TAG, "createDirectory error: " + e.toString());
}
return directory;
}
Call the Files.create API to create a file. The are two methods for uploading a file: direct upload and resumable upload. The direct upload method allows a file of up to 20 MB to be uploaded while the resumable upload method does not have such a limit. The direct upload method is recommended for files smaller than 5 MB and the resumable upload method for files larger than 5 MB.
Method 1: Directly upload the file.
Code:
/**
* Upload a file. This method supports resumable upload.
* (The upload operation resumes after it is interrupted by a communication failure, for example, network interruption.)
*
* @param filePath File path.
* @param parentId ID of the folder to which the file is to be uploaded.
* @param thumbnailImageBuffer Thumbnail data.
* @param thumbnailMimeType MIME type of the thumbnail.
*/
private void createFile(String filePath, String parentId, byte[] thumbnailImageBuffer, String thumbnailMimeType) {
try {
if (filePath == null) {
Logger.e(TAG, "createFile error, filePath is null.");
return;
}
java.io.File file = new java.io.File(filePath);
FileContent fileContent = new FileContent(null, file);
// Set thumbnail data.
File.ContentExtras contentExtras = new File.ContentExtras();
File.ContentExtras.Thumbnail thumbnail = new File.ContentExtras.Thumbnail();
thumbnail.setContent(Base64.encodeBase64String(thumbnailImageBuffer));
thumbnail.setMimeType(thumbnailMimeType);
contentExtras.setThumbnail(thumbnail);
File content = new File()
.setFileName(file.getName())
.setParentFolder(Collections.singletonList(parentId))
.setContentExtras(contentExtras);
Drive drive = buildDrive();
Drive.Files.Create request = drive.files().create(content, fileContent);
boolean isDirectUpload = false;
// Directly upload the file if it is smaller than 20 MB.
if (file.length() < DIRECT_UPLOAD_MAX_SIZE) {
isDirectUpload = true;
}
// Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
request.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
request.execute();
} catch (Exception e) {
Logger.e(TAG, "createFile exception: " + filePath + e.toString());
}
}
Method 2: Upload the file using InputStream.
Code:
/**
* Upload the file using InputStream.
*
* @param inputStream Input stream, from which file data is read.
* @param parentId ID of the folder to which the file is to be uploaded.
* @param mimeType MIME type, for example, image (jpeg) and video (mp4).
* @param inputStreamLength Stream length.
*/
private void createFile(InputStream inputStream, String parentId, String mimeType, int inputStreamLength) {
try {
InputStreamContent streamContent = new InputStreamContent(mimeType, inputStream);
streamContent.setLength(inputStreamLength);
File content = new File()
.setFileName("video.mp4")
.setParentFolder(Collections.singletonList(parentId));
Drive drive = buildDrive();
drive.files().create(content, streamContent).execute();
} catch (Exception e) {
Logger.e(TAG, "createFile exception: " + e.toString());
}
}
Call the Files.copy API to copy the file.
Code:
/**
* Copy the file to the designated folder.
*
* @param file File to be copied.
* @param dstDir Designated folder.
*/
private void copyFile(File file, ArrayList<String> dstDir) {
try {
File copyFile = new File();
if (file == null || file.getFileName() == null ||dstDir == null) {
Log.e(TAG, "copyFile arguments error");
sendHandleMessage(R.id.drive_files_button_copy, FAIL);
return;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String suffix = formatter.format(new Date());
copyFile.setFileName(file.getFileName() + "_copy" + "_" + suffix);
copyFile.setDescription("copyFile");
copyFile.setParentFolder(dstDir);
copyFile.setFavorite(true);
copyFile.setEditedTime(new DateTime(System.currentTimeMillis()));
Drive drive = buildDrive();
Drive.Files.Copy copyFileReq = drive.files().copy(file.getId(), copyFile);
copyFileReq.setFields("*");
File result = copyFileReq.execute();
} catch (IOException ex) {
Log.e(TAG, "copyFile error: " + ex.toString());
}
}
Call the Files.update API to modify the metadata of the file or folder.
Code:
/**
* Modify the file or folder. The value of MIMEType indicates whether it is a file or a folder.
*
* @param file File or folder to be modified.
*/
private void updateFile(File file) {
try {
if (file == null) {
Logger.e(TAG, "updateFile error, need to create file.");
return;
}
Drive drive = buildDrive();
File updateFile = new File();
updateFile.setFileName(file.getFileName() +"_update")
.setMimeType("application/vnd.huawei-apps.folder")
.setDescription("update folder")
.setFavorite(true);
drive.files().update(file.getId(), updateFile).execute();
} catch (Exception e) {
Logger.e(TAG, "updateFile error: " + e.toString());
}
}
Call the Files.update API to modify the metadata or content of the file.
Code:
/**
* Modify the file.
*
* @param oldFile File to be modified.
* @param newFilePath Path storing the modified file.
*/
private void updateFile(File oldFile, String newFilePath) {
try {
if (oldFile == null || TextUtils.isEmpty(newFilePath)) {
Logger.e(TAG, "updateFile error, need to create file.");
return;
}
java.io.File sourceFile = new java.io.File(newFilePath);
FileContent fileContent = new FileContent(null, sourceFile);
File updateFile = new File();
updateFile.setFileName(oldFile.getFileName() + "_update")
.setDescription("update folder")
.setFavorite(true);
Drive drive = buildDrive();
Drive.Files.Update update = drive.files().update(oldFile.getId(), updateFile, fileContent);
boolean isDirectUpload = false;
// Directly upload the file if it is smaller than 20 MB.
if (sourceFile.length() < DIRECT_UPLOAD_MAX_SIZE) {
isDirectUpload = true;
}
// Set the upload mode. By default, resumable upload is used. If the file is smaller than 20 MB, set this parameter to true.
update.getMediaHttpUploader().setDirectUploadEnabled(isDirectUpload);
update.execute();
} catch (Exception e) {
Logger.e(TAG, "updateFile error: " + e.toString());
}
}
Call the Files.delete API to permanently deletes a file or folder.
Code:
/**
* Permanently deletes a file or folder.
*
* @param file File or folder to be deleted.
*/
private void deleteFile(File file) {
try {
Drive drive = buildDrive();
Drive.Files.Delete deleteFile = drive.files().delete(file.getId());
deleteFile.execute();
} catch (IOException ex) {
Log.e(TAG, "deleteFile error: " + ex.toString());
}
}
Call the Files.get API to obtain the file metadata.
Code:
/**
* Obtain the file metadata.
*
* @param fileId File ID.
*/
private File getFileMetadata(String fileId) {
File file = null;
try {
Drive drive = buildDrive();
Drive.Files.Get request = drive.files().get(fileId);
request.setFields("*");
file = request.execute();
} catch (Exception e) {
Logger.e(TAG, "get metadata error: " + e.toString());
}
return file;
}
Call the Files.get API to download the file metadata and content. A file of any size can be downloaded. To download a file smaller than 20 MB, set directDownloadEnabled to true. Then, simply download the file through a network request.
Code:
/**
* Download the file metadata and content.
*
* @param fileId File ID.
* @param destFile Target file.
*/
private void downLoadFile(String fileId, java.io.File destFile) {
if (fileId == null || destFile == null) {
return;
}
try {
Drive drive = buildDrive();
Drive.Files.Get request = drive.files().get(fileId);
File fileContent = request.execute();
long size = fileContent.getSize();
Drive.Files.Get downloadRequest = drive.files().get(fileId);
MediaHttpDownloader downloader = downloadRequest.getMediaHttpDownloader();
boolean isDirectDownload = false;
// Download the file using the simple download method if it is smaller than 20 MB.
if (size < DIRECT_DOWNLOAD_MAX_SIZE) {
isDirectDownload = true;
}
// Set the range. This parameter is mandatory when the simple download method is not uesd.
downloader.setContentRange(0, size - 1);
// Set the download method. By default, a download method rather than simple download is used. If the file is smaller than 20 MB, set this parameter to true.
downloader.setDirectDownloadEnabled(isDirectDownload);
// Set the progress callback listener.
downloadRequest.getMediaHttpDownloader().setProgressListener(new MediaHttpDownloaderProgressListener() {
@Override
public void progressChanged(MediaHttpDownloader downloader) throws IOException {
// Download progress notification.
}
});
downloadRequest.executeContentAndDownloadTo(new FileOutputStream(destFile));
} catch (Exception e) {
Logger.e(TAG, "download file error:" + fileId + e.getMessage());
if (destFile != null) {
// If the download fails, delete the temporary file.
if (destFile.exists()) {
boolean isDeleteSuccess = destFile.delete();
if (!isDeleteSuccess) {
Logger.e(TAG, "downLoadFile delete file fail");
}
}
}
}
}
Call the Files.list API to search for files.
Code:
/**
* Search for files.
* @param query Query parameter. For details, please refer to Q statements.
* @param orderBy Sorting field.
* @param pageSize Maximum number of files to return per page.
* @param fields Fields to be contained in the response.
*/
private List<File> getFileList(String query, String orderBy, int pageSize, String fields){
List<File> fileList = null;
try{
Drive drive = buildDrive();
Drive.Files.List request = drive.files().list();
String cursor = null;
fileList = new ArrayList<>();
do {
FileList result = null;
result = request.setQueryParam(query)
.setOrderBy(orderBy)
.setPageSize(pageSize)
.setFields(fields)
.execute();
for (File file : result.getFiles()) {
fileList.add(file);
}
cursor = result.getNextCursor();
request.setCursor(cursor);
}while(!StringUtils.isNullOrEmpty(cursor));
}catch (Exception e) {
Logger.e(TAG, "executeFilesList exception: " + e.toString());
}
return fileList;
}
Call the Files.subscribe API to register the channel for tracking changes made to the designated file and enable change notification for the file.
Code:
/**
* register to the channel for tracking changes made to the designated file and enable change notification for the file.
*
* @param fileId File ID
*/
private void filesWatch(String fileId) {
try {
Drive drive = buildDrive();
Channel content = new Channel();
content.setType("web_hook");
content.setUrl("https://xxxx.com"); // Address of the server to which file changes will be sent. You need to build the server.
Drive.Files.Subscribe request = drive.files().subscribe(fileId, content);
Channel channel = request.execute();
SharedPreferences prefs = context.getSharedPreferences("channel_config", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("id", channel.getId());
editor.putString("resourceId", channel.getResourceId());
editor.commit();
} catch (Exception e) {
Log.e(TAG, "Exception" + e.getCause());
}
}

Defining custom components on HarmonyOS

They're custom components!,...are you telling me...you've never heared of them..!?
Hi, my name's Younes Megaache, and in this tutorial, I will teach you about custom component on harmonyOS. or at least I wll try LOL!
Am I doing this right? The first sentence is always the hardest!.
We will be creating creating two (2) custom components, a compound component and a custmized one. After reading this article and checking the demo code, you should have learned enough to start creating you're own custome components, or may be not XD!.
You can find links below with more details on this topic.
The code is uploaded to github, the link can be found at the end of the article (bottom).
Table of content
Overview
Create component 1: SButton (compound component)
Define custom component class.
Define custom component layout.
Add component to layout.
Define custom attributes.
Apply custom attributes.
Finishing the components.
Create component 2: ShapeShiftingComponent
Define custom component class.
Add component to layout.
Define custom attributes.
Apply custom attributes.
Drawing a shape
Toggling between shapes
Finishing the component
Tips and tricks
Libraries
Github project (source code)
References
Overview​HarmonyOS UI elements are all based on Component (single element on screen) and ComponentContainer (collection of elements on screen). There are many "widgets" and "layouts" built-in that can be used to build the UI such as components like Button and Text, and component containers like DirectionalLayout and StackLayout.
In some apps though we need to be able to customize components to suit our own needs. This might mean extending an existing component or creating your own Component subclass.
Customizing your own components involves extending Component or an existing subclass, overriding the component behavior by writing methods such as onDraw or onTouchEvent and then using your new component in an ability.
Creating custom components is centered around 4 primary aspects that we may need to control or modify:
Drawing: Control the rendering of the component on screen visually by adding draw tasks and overriding the onDraw method.
Interaction: Control the ways the user can interact with the component with the onTouchEvent and gestures.
Measurement: Control the content dimensions of the component on screen by overriding the onEstimateSize method.
Attributes: Defining custom XML attributes for your component and using them to control behavior with TypedArray
To take a closer look, we will create two components:
first, we will create a compound component where we will be putting together multiple components as one
second, suppose we want to create our own component control that allows the user to select between different shapes. The component will display a single shape (rectangle, circle or triangle) and clicking on the component will toggle the shape selected between the different options.
Before we start: some resources like colors, strings, backgrounds are not included in this article, visit the github project for full code
Component 1: SButton (compound component) ​The first component that we'll be creating is a compound button, which will consist of an icon, text and an arrow, This will help us understand creating a reusable component by putting together multiple components .
Define Custom component Class​To create our own custom component, we start by defining a SButton which extends from StackLayout, as it's a ComponentContainer that will host multiple components. then implement the required constructor:
Java:
public class SButton extends StackLayout {
public SButton(Context context, AttrSet attrSet) {
super(context, attrSet);
}
}
Define custom component layout​Create a layout file component_sbutton.xml, which will hold 3 components as described earlier:
XML:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="center"
ohos:orientation="horizontal"
ohos:padding="3vp"
>
<DirectionalLayout
ohos:id="$+id:button_root"
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="center"
ohos:background_element="$graphic:bg_button_red"
ohos:orientation="horizontal"
>
<DirectionalLayout
ohos:height="match_content"
ohos:width="match_parent"
ohos:alignment="center"
ohos:bottom_margin="3vp"
ohos:left_margin="10vp"
ohos:min_height="40vp"
ohos:orientation="horizontal"
ohos:right_margin="10vp"
ohos:top_margin="3vp"
>
<Image
ohos:id="$+id:button_icon"
ohos:height="30vp"
ohos:width="28vp"
ohos:clip_alignment="center"
ohos:image_src="$media:icon"
ohos:layout_alignment="center"
ohos:scale_mode="clip_center"
ohos:visibility="visible"
ohos:weight="1.2"
/>
<Text
ohos:id="$+id:button_text"
ohos:height="match_content"
ohos:width="match_content"
ohos:left_margin="5vp"
ohos:multiple_lines="true"
ohos:text="Button"
ohos:text_alignment="center"
ohos:text_color="white"
ohos:text_size="18fp"
ohos:text_weight="700"
ohos:weight="5"
/>
<Text
ohos:id="$+id:button_arrow"
ohos:height="match_parent"
ohos:width="match_content"
ohos:left_margin="10vp"
ohos:text="→"
ohos:text_color="white"
ohos:text_size="20fp"
ohos:text_weight="800"
ohos:visibility="visible"
ohos:weight="1"
/>
</DirectionalLayout>
</DirectionalLayout>
</DirectionalLayout>
The component has a default red background defined in graphic/bg_button_red.xml:
XML:
<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:shape="rectangle">
<solid
ohos:color="$color:red"/>
<corners
ohos:radius="50"/>
</shape>
In the previewer you should see this:
Let's set set the layout and initialize the components before we move to the attributes :
Java:
public class SButton extends StackLayout {
//...
/**
* root layout, parent of other components {@link com.megaache.customcomponent.ui.components.SButton#textC} {@link com.megaache.customcomponent.ui.components.SButton#iconC} {@link com.megaache.customcomponent.ui.components.SButton#arrowC}
*/
private DirectionalLayout root;
/**
* button text, shown in the center of the button
*/
private Text textC;
/**
* icon component shown on the left side of the button's text
*/
private Image iconC;
/**
* arrow component shown on the rigth side of button's text
*/
private Text arrowC;
public SButton(Context context, AttrSet attrSet) {
super(context, attrSet);
LayoutScatter.getInstance(getContext())
.parse(ResourceTable.Layout_component_sbutton, this, true);
root = (DirectionalLayout) findComponentById(ResourceTable.Id_button_root);
textC = (Text) findComponentById(ResourceTable.Id_button_text);
arrowC = (Text) findComponentById(ResourceTable.Id_button_arrow);
iconC = (Image) findComponentById(ResourceTable.Id_button_icon);
}
}
Add Component to Layout​Next, let's add this component to our ability layout:
Code:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
xmlns:sbutton="http://huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="black"
ohos:orientation="vertical"
ohos:padding="20vp"
>
<com.megaache.customcomponent.ui.components.SButton
ohos:id="$+id:sbutton"
ohos:height="match_content"
ohos:width="200vp"
ohos:layout_alignment="horizontal_center"
/>
</DirectionalLayout>
Note: how we define a custom namespace SButton. This namespace allows you to allow Harmony to auto-resolve the namespace, avoiding the annoying IDE errors
this is the component in its default state:
Define Custom Attributes
Well-written custom components can be configured and styled via XML attributes. You need to ask yourself which aspects of your component should be customizable. For example, we might want to let the user set the background (color) of the button, set icon source, set the button's text as well as give the developer the option to hide or show an arrow icon. We might want the component to be configurable in XML as follows:
XML:
<com.megaache.customcomponent.ui.components.SButton
ohos:id="$+id:sbutton"
ohos:height="match_content"
ohos:width="200vp"
ohos:layout_alignment="horizontal_center"
sbutton:btn_bg="$graphic:button_violet"
sbutton:icon_src="$media:phone"
sbutton:show_arrow="true"
sbutton:text="$string:hello"
/>
Once you define the custom attributes, you can use them in layout XML files, You won't get similar experience like built-in attributes (autocomplete) and that's because DevEco studio does not support defining the attribute format yet!.
A difference between custom attributes and built-in attribute is that your custom attributes belong to a different namespace. You can define the namespace within the root component of the layout and configure the properties for the component. You would need to use the namespace http://huawei.com/res/ohos:
XML:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
xmlns:sbutton="http://huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="black"
ohos:orientation="vertical"
ohos:padding="20vp"
>
<com.megaache.customcomponent.ui.components.SButton
ohos:id="$+id:sbutton"
ohos:height="match_content"
ohos:width="200vp"
ohos:layout_alignment="horizontal_center"
sbutton:btn_bg="$graphic:button_violet"
sbutton:icon_src="$media:phone"
sbutton:show_arrow="true"
sbutton:text="$string:hello"
/>
</DirectionalLayout>
Apply Custom Attributes​Now that we have set custom properties such as btn_bg, icon_src, show_arrow and text, we need to extract those properties to be used within our custom component within the constructor, from AttrSet parameter:
First, let's created an inner class that will hold the attribute name, to keep our code clean:
Java:
public class SButton extends StackLayout {
public static class SButtonAttrsConstants {
//if set to true, arrow will be shown on right side of the text
public static final String SHOW_ARROW = "show_arrow";
//if set, icon will be shown on left side of text
public static final String ICON_SRC = "icon_src";
//text to be shown in the button
public static final String BTN_TEXT = "text";
//background for the container
public static final String BTN_BG = "btn_bg";
}
//...
}
The attributes are passed to the custom component inside AttrSet parameter, We are gonna use the method ifPresent when extracing the attribute for safety:
Java:
attrSet.getAttr("attribute_name").ifPresent(attr -> attr.getStringValue() )
There are seven (7) types of attribute, make sure to use the right method to get the attribute value according to its format:
String: ex app:text="blah blah", app:text="$string:blah_blah"
Code:
attr.getStringValue();
Integer, ex app:number="1"
Code:
attr.getIntegerValue();
graphic or media, ex app:graphic="$graphic:bg_red", app:icon="$media:banana"
Code:
attr.getElement();
Boolean, ex app:hide="true"
Code:
attr.getBoolValue();
Dimension, ex app:dimen="2vp"
Code:
attr.getDimensionValue();
Float, ex app:float="22.34"
Code:
attr.getFloatValue();
Long, ex app:long="1234543212345"
Code:
attr.getLongValue();
extracting the attribute values:
Code:
public class SButton extends StackLayout {
//...
public SButton(Context context, AttrSet attrSet) {
super(context, attrSet);
//...
if (attrSet != null) {
attrSet.getAttr(SButtonAttrsConstants.SHOW_ARROW).ifPresent(attr -> setShowArrow(attr.getBoolValue()));
attrSet.getAttr(SButtonAttrsConstants.BTN_TEXT).ifPresent(attr -> setText(attr.getStringValue()));
attrSet.getAttr(SButtonAttrsConstants.BTN_TEXT).ifPresent(attr -> setText(attr.getIntegerValue()));
attrSet.getAttr(SButtonAttrsConstants.ICON_SRC).ifPresent(attr -> setIconRes(attr.getElement()));
attrSet.getAttr(SButtonAttrsConstants.BTN_BG).ifPresent(attr -> setBg(attr.getElement()));
}
}
//...
}
then we write some logic to update the component based on the attributes:
Java:
public class SButton extends StackLayout {
//...
/**
* set button text
*
* @param textRes resource id of text that will be shown inside button
*/
public void setText(int textRes) {
if (textRes != -1) {
this.textC.setText(textRes);
}
}
/**
* show icon on left side of the text
*
* @param imageElement image element ex: {@link ResourceTable#Media_phone}
* if imageElement is null, the icon component will be hidden
*/
public void setIconRes(Element imageElement) {
if (imageElement == null) {
UiUtils.hide(iconC);
} else {
imageElement.setBounds(0, 0, iconC.getRight(), iconC.getBottom());
iconC.setImageElement(imageElement);
UiUtils.visible(iconC);
}
}
/**
* set button text
*
* @param text will be shown inside button
*/
public void setText(String text) {
if (text != null && !text.isEmpty()) {
this.textC.setText(text);
}
}
/**
* show arrow on right side of the text
*
* @param showArrow true to show an arrow, false otherwise
*/
public void setShowArrow(boolean showArrow) {
if (showArrow)
UiUtils.visible(arrowC);
else
UiUtils.hide(arrowC);
}
/**
* change button background
*
* @param shapeElement element that will be set as background
*/
public void setBg(Element shapeElement) {
root.setBackground(shapeElement);
}
}
Finishing the Component​Finally, lets add some animation to our custom component which is totally optional:
Java:
public class SButton extends StackLayout {
//...
@Override
public void setClickedListener(ClickedListener listener) {
super.setClickedListener((c) -> {
animateTouchDown();
getContext().getUITaskDispatcher().delayDispatch(() -> {
animateTouchUp();
listener.onClick(c);
}, 300);
});
}
/**
* scale button up when clicked, called when the button is clicked
*/
private void animateTouchDown() {
setScale(1.1f, 1.1f);
setAlpha(0.5f);
}
/**
* scale button down to normal size, called when the button is clicked
*/
private void animateTouchUp() {
setScale(1, 1);
setAlpha(1f);
}
}
then within the ability, we can display a toast when the button is clicked:
Java:
public class MainAbility extends Ability {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
setUIContent(ResourceTable.Layout_ability_main);
SButton sButton = (SButton) findComponentById(ResourceTable.Id_sbutton);
sButton.setClickedListener(c -> toast("you clicked the SButton!"));
}
private void toast(String msg) {
new ToastDialog(this).setText(msg).setAlignment(LayoutAlignment.CENTER).show();
}
}
Run the app:
Component 2: ShapeShiftingButton​The second component that we will be creating is a fully custom “shape shifting”‘component that changes it’s shape when it’s clicked.
Define Custom Component Class​We start by defining a ShapeShiftingComponent which extends from Component and implements the required constructor:
Java:
public class ShapeShiftingComponent extends Component {
public ShapeShiftingComponent(Context context, AttrSet attrSet) {
super(context, attrSet);
}
}
Add Component to Layout​Next, let's add this component to our ability layout:
XML:
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
xmlns:app="http://huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:background_element="black"
ohos:orientation="vertical"
ohos:padding="20vp"
>
<com.megaache.customcomponent.ui.components.ShapeShiftingComponent
ohos:id="$+id:ssbutton"
ohos:height="80vp"
ohos:width="160vp"
ohos:layout_alignment="horizontal_center"
ohos:text_color="white"
ohos:text_size="18fp"
ohos:top_margin="20vp"
/>
</DirectionalLayout>
Define Custom Attributes​for this component, we can let the user set the initial shape which can be done as follow:
XML:
<com.megaache.customcomponent.ui.components.ShapeShiftingComponent
ohos:id="$+id:ssbutton"
ohos:height="80vp"
ohos:width="160vp"
ohos:layout_alignment="horizontal_center"
ohos:text_color="white"
ohos:text_size="18fp"
ohos:top_margin="20vp"
app:shape="rectangle"
app:shape_color="#ff0000"
/>
Apply Custom Attributes​We have set custom attribute shape and shape_color lets extract this attribute from AttrSet parameter.
Lets declare the attribute name in separate class:
Java:
public class ShapeShiftingComponent extends Component {
public static class CSButtonAttrsConstants {
public static final String CSBUTTON_SHAPE = "shape";
public static final String CSBUTTON_SHAPE_COLOR = "shape_color";
}
}
Lets extract the values of attributes which will be used within the constructor of our component:
Java:
public class ShapeShiftingComponent extends Component {
//...
public static class CSButtonAttrsConstants {
public static final String CSBUTTON_SHAPE = "shape";
public static final String CSBUTTON_SHAPE_COLOR = "shape_color";
}
/**
* button shape, can be set inside layout file, ex: app:shape="rectangle"
* must be one of: rectangle, circle, triangle
*/
private String shape;
/**
* the color of the shape, can be set using attribute inside layout (xml) file
*/
private Color shapeColor;
public ShapeShiftingComponent(Context context, AttrSet attrSet) {
super(context, attrSet);
if (attrSet != null) {
attrSet.getAttr(CSButtonAttrsConstants.CSBUTTON_SHAPE)
.ifPresent(attr -> shape = attr.getStringValue());
attrSet.getAttr(CSButtonAttrsConstants.CSBUTTON_SHAPE_COLOR)
.ifPresent(attr -> shapeColor = attr.getColorValue());
}
}
//...
}
Drawing a shape​Next, let's actually draw a rectangle taking into account shape color. we will use addDrawTask to draw the shape for now, in future releases of HarmonyOs SDK, the components will have method onDraw where you can draw shapes:
Java:
public class ShapeShiftingComponent extends Component {
//...
/**
* the color of the shape, can be set using attribute inside layout (xml) file
*/
private Color shapeColor;
/**
* WIDTH of the button, used to draw shape using canvas in {@link ShapeShiftingComponent#drawShape}
*/
public static final int WIDTH = 160;
/**
* HEIGHT of the button, used to draw shape using canvas in {@link ShapeShiftingComponent#drawShape}
*/
public static final int HEIGHT = 80;
/**
* the y offset of the text that's shown inside the component (button)
*/
public static final int TEXT_Y_OFFSET = HEIGHT / 2 + 5;
/**
* size of the text that's shown inside the component (button)
*/
public static final int TEXT_SIZE_FP = 20;
/**
* paint used to draw the shapes, defines the color of the shape
* used in {@link ShapeShiftingComponent#drawShape()}
*/
private Paint shapePaint;
/**
* paint used to draw the text (shape name), it defines the color and font size of the text
* used in {@link ShapeShiftingComponent}
*/
private Paint textPaint;
public ShapeShiftingComponent(Context context, AttrSet attrSet) {
super(context, attrSet);
//...
preparePaint();
drawShape();
}
/**
* add draw task to draw shape and it's name (shape)
*/
private void drawShape() {
addDrawTask((component, canvas) -> {
//draw rectangle
canvas.drawRect(0, 0, toPx(WIDTH), toPx(HEIGHT), shapePaint);
//draw text 'rectangle' inside shape
canvas.drawText(textPaint, shape, toPx(WIDTH / 2 - (9 * shape.length() / 2)), toPx(TEXT_Y_OFFSET));
});
}
/**
* convert VP (visual/density pixel) to pixels
*
* @param vp value in VP (density pixel)
* @return value in pixels
*/
private float toPx(int vp) {
return AttrHelper.vp2px(vp, getContext());
}
/**
* initial paint objects, that are used to draw the shape and text (shape name)
*/
private void preparePaint() {
shapePaint = new Paint();
shapePaint.setStyle(Paint.Style.FILL_STYLE);
shapePaint.setColor(shapeColor);
textPaint = new Paint();
textPaint.setStyle(Paint.Style.FILL_STYLE);
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(AttrHelper.fp2px(TEXT_SIZE_FP, getContext()));
}
}
this will draw the shape based on the attributes shape and shape_color defined in XML layout file:
you can set the attribute shape to circle:
or triangle:
Toggling between shapes​Now, to make our custom component stand to its name, we have to make it change shape each time it's clicked.
Let's setup a "clicked listener" to invalidate the layout to force re-draw the component:
Java:
public class ShapeShiftingComponent extends Component {
//...
public static final String CIRCLE = "circle";
public static final String RECTANGLE = "rectangle";
public static final String TRIANGLE = "triangle";
private final String[] shapes = new String[]{RECTANGLE, TRIANGLE, CIRCLE};
/**
* button shape, can one of {@link ShapeShiftingComponent#shapes}
*/
private String shape;
/**
* used to loop through the array of shapes {@link ShapeShiftingComponent#shapes}
*/
private int shapeIndex;
public ShapeShiftingComponent(Context context, AttrSet attrSet) {
super(context, attrSet);
//...
registerListener();
}
/**
* register click listener to change shape everytime the component is clicked
*/
private void registerListener() {
this.setClickedListener(c -> {
shapeIndex++;
shape = shapes[shapeIndex % shapes.length];
invalidate();
postLayout();
});
}
//...
}
Now whenever the shape is clicked, the selected shape is changed and the OS should call our drawing task once again.
Let's update our draw task to handle drawing other shapes (circle, triangle):
Java:
public class ShapeShiftingComponent extends Component {
//...
public static final int CIRCLE_RADIUS = 120;
/**
* add draw task to draw the next shape of the component, and it's name (shape)
* also show toast for the current shape
*/
private void drawShape() {
addDrawTask((component, canvas) -> {
new ToastDialog(getContext())
.setAlignment(LayoutAlignment.CENTER)
.setText("shape:" + shape).show();
switch (shape) {
case CIRCLE: {
Point center = new Point(WIDTH * 1.5f, HEIGHT * 1.5f);
canvas.drawCircle(center, CIRCLE_RADIUS, shapePaint);
break;
}
case TRIANGLE: {
Path trianglePath = new Path();
trianglePath.moveTo(0, HEIGHT * 2); //bottom left
trianglePath.lineTo(WIDTH * 3, HEIGHT * 2); //bottom right
trianglePath.lineTo(WIDTH * 1.5f, 0); //center
canvas.drawPath(trianglePath, shapePaint);
break;
}
default: {
canvas.drawRect(0, 0, toPx(WIDTH), toPx(HEIGHT), shapePaint);
}
}
canvas.drawText(textPaint, shape, toPx(WIDTH / 2 - (9 * shape.length() / 2)), toPx(TEXT_Y_OFFSET));
});
}
//...
}
Finishing the component​The final touch is to add the default values: or may be this should have been the first step LOL!
Java:
public class ShapeShiftingComponent extends Component {
//...
public ShapeShiftingComponent(Context context, AttrSet attrSet) {
super(context, attrSet);
setDefaultValues();
//...
}
/**
* set the default values, in case the developer didn't specify the values in layout file (xml)
*/
private void setDefaultValues() {
shape = RECTANGLE;
shapeColor = new Color(getContext().getColor(ResourceTable.Color_ssbutton_default));
shapeIndex = 0;
}
//...
}
Run the app, click the component to loop throught the shapes:
Tips and tricks​
There are many other things to cosider when creating custom component, like measurements or touch events, check out the custom component guide on the official website.
If you have an existing custome component that's similar to what you want to create, you can simlply extend that custom component and just override the behavior that you want and get the rest for free
You can also create a custom layout by extending ComponetContainer, to act as a container for your other components
To run the project you're advised to HVD manager to test on a remote device, If you want to run the project on a physical device then you have to configure the signin config (last link in references)
Libraries​there are some libraries for harmonyOs that have custom comopnents, you can check some picks below. the libraries are open source so you may wanna have a look at the source code to learn more:
BadgeView: https://gitee.com/openharmony-tpc/BadgeView
CircleImageView: https://gitee.com/openharmony-tpc/CircleImageView
ArcProgresssStackView: https://gitee.com/openharmony-tpc/ArcProgressStackView
Github project ​Click here
References​
https://developer.harmonyos.com/en/docs/documentation/doc-guides/ui-java-custom-components-0000001139369661
https://developer.harmonyos.com/en/docs/documentation/doc-guides/ui-java-custom-layouts-0000001092683918
https://developer.harmonyos.com/en/docs/documentation/doc-references/component-0000001054678683
https://developer.harmonyos.com/en/docs/documentation/doc-guides/build_hap-0000001053342418
sorry If the links are not clickable, it's not on me
Original Source
Thanks for reading!
How to set the size and color of button inside custom class which extends Stack Layout?

Categories

Resources