[RHBROMS][Android Test Automation Tool][Tutorials] ROBOTIUM v5.2.1 with Recorder v2.0 - Android General

{
"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"
}
Presents
Table of Contents:
1. Robotium
2. What all we need before we get it started?
3. How to setup Robotium using Eclipse ADT with source code of Android Application?
3a. Basic Android Test Project with source code
4. How to setup Robotium using Eclipse ADT without source code of Android Application?
4a. Basic Android Test Project without source code
5. What is JUnit Test Suite and why we need it with Robotium?
6. How to Data-Drive Robotium Scripts?
7. Issues or challenges with Robotium
Please skip to second post If you are reading this post for the first time​
ROBOTIUM 5.2.1 Released​
New Features and bug Fix details:​
unlockScreen() - Unlocks the screen lock.
getCurrentViews(Class<T> classToFilterBy, boolean includeSubclasses) - New parameter includeSubclasses set to true if also subclasses should be returned.
scrollToSide(Side side, float scrollPosition, int stepCount) - Added parameter stepCount to allow for users to decide the speed of the scroll.
scrollViewToSide(View view, Side side, float scrollPosition, int stepCount) - Added parameter stepCount to allow for users to decide the speed of the scroll.
Bugs fixed:
Issue-600 - ViewFetcher, getRecentDecorView fails on Samsung S4 with MultiWindow support
Issue-579 - Screenshots do not get saved
Issue-589 - waitForFragment on vers < 3.0
Issue-615 - ScrollToSide opens the navigation bar
I hope you will enjoy this release!
Link To Download: CLICK HERE
Robotium Recorder 2.0 is released!
From,
Renas Reda
Founder and CEO at Robotium Tech
We're excited to announce the release of Robotium Recorder 2.0. Thanks to all the feedback that we've received, we've been able to make hundreds of improvements since it first launched. It's now compatible with more apps and is optimized to generate even smarter tests than before.
New in Robotium Recorder 2.0:
- Improved click and gesture support.
- Click to Assert™ has been further refined and is now performing optimally in a broad range of apps.
- Record click and drag coordinates by selecting the option in "Settings".
- Full support for GL apps and games by enabling touch and drag coordinates.
- After a test case has been saved it can now be executed directly from Robotium Recorder by clicking "Run Test".
Robotium Recorder 2.0 comes with a new trial period, so even if you have consumed the trial of the old version you are now able to try this new version as well.
To update Robotium Recorder, in Eclipse go to Help --> "Check for updates"
Details on how to install explained in the Old posts below.​
````````````````````````````````````````````````````````````````````````````````````````````````````` ````````````````````````````````````````````````````
OLD POSTS
:victory:ROBOTIUM 5.0.1 Got Released !!! :victory:
Robotium Rec. Latest Update: 1.4.11 (23/01/14)
Robotium Recorder updates are releasing almost daily.. The first update what I got was 1.2.95 and now we have the latest update as 1.4.5 (22/01/14). I will be updating this post as I find new updates...
Click to expand...
Click to collapse
Renas Reda
Founder and maintainer of Robotium
said,
We're happy to announce the release of Robotium 5.0.1! Included in this release is a new Config class, where Robotium Developers can change various things like default timeouts, screenshot location, screenshot type, scrolling, and web element click behaviour.
We’ve been working hard on improving the various click methods by testing numerous popular apps under sub-par performances to add further logic to the click methods and thus reduce click issues. In the last year we’ve gone through the whole code base and improved various areas. This is an update we recommend for everyone using older Robotium versions.
Click to expand...
Click to collapse
The new changes in 5.0.1 are as follows,
NOTE: The package name has been changed to com.robotium.solo. You’ll need to update the import line at the top of your current test classes from com.jayway.android.solo to com.robotium.solo.
New functionality in Robotium 5.0.1:
pressSoftKeyboardNextButton() - Presses the next button on the soft keyboard.
waitForEmptyActivityStack(int timeout) - Waits until the Activity stack is empty.
New Class com.robotium.solo.Solo.Config:
int timeout_large - The timeout length of the waitFor methods. Default length is 20 000 milliseconds.
int timeout_small - The timeout length of the get, is, set, assert, enter and click methods. Default length is 10 000 milliseconds.
String screenshotSavePath - The screenshot save path. Default save path is /sdcard/Robotium-Screenshots/.
ScreenshotFileType screenshotFileType - The screenshot file type, JPEG or PNG. Use ScreenshotFileType.JPEG or ScreenshotFileType.PNG. Default file type is JPEG.
boolean shouldScroll - Set to true if the get, is, set, enter, type and click methods should scroll. Default value is true.
boolean useJavaScriptToClickWebElements - Set to true if JavaScript should be used to click WebElements. Default value is false.
Improvements:
All the click methods. Improved behaviour in unfavorable situations.
The waitForDialogToOpen & waitForDialogToClose methods. Now recognises all dialogs.
The internal View handling class.
TakeScreenshot() now supports GLSurfaceViews with OpenGL ES 3.0.
See the Javadoc for an example on how to use the new Config class.
We hope you will enjoy this release!
https://code.google.com/p/robotium/downloads/list
This will be a Full Tutorial on Robotium Android Automation Tool
I will be updating this thread as I get time. SO NO ETA's.
Click to expand...
Click to collapse
If anybody wants to use / copy this tutorial to their Website or Blog please feel free to contact me at my personal email id: [email protected]
or at our official Website: www.rhbroms.com
Click to expand...
Click to collapse
Please Click on Thanks button if this tutorial by me had helped you for some extent !!!
Click to expand...
Click to collapse
User Guide for Robotium Recorder ( Skip this guide if you are reading this post for the first time and move on with the second post..)
Link to Robotium Official website: Click Here
Prerequisites:
Install Robotium Recorder, if not already installed.
Connect a device (recommended) or start an emulator with external storage.
Start Robotium Recorder
Start Robotium Recorder from the toolbar: Eclipse > New > Other > Android - Robotium Recorder.
Robotium Recorder can also be started by right clicking an existing app or test project and from the opened menu select: Robotium Recorder > New Robotium Test.
Record test cases from a workspace project
From Robotium Recorder it's possible to select either a binary (APK file) or a workspace project to record test cases from. In the screenshot below a workspace project has been selected. Enter a test project name and click "Next".
Record test cases from a binary APK
To record test cases from an APK, click "select apk". A file browser will be opened where the APK can be selected. Robotium Recorder will automatically sign the APK with the local debug certificate.
Once the signing process has finished the "Next" button will be enabled.
Start recording
Clicking Next on the previous screen will show the recording screen.
In the left bottom corner there is Setting menu with three options:
a. Use sleeps - choose if sleeps should be used to playback test cases in the same speed as they were recorded. Can be useful for slower apps like bandwidth intensive or hybrid apps.
b. Keep app data - choose if app data is to be kept when starting a new recording session.
c. Identify class over string - default View identifier is always the resource ID. In the event a resource ID is missing it's possible to choose if a View class identifier is to be used over a string identifier (the text displayed by the View).
Click "New Robotium Test".
If an APK is selected, Robotium Recorder will first install the re-signed APK on the device or emulator.
When installation of the workspace project or APK is done the recording will be started.
The app is executed on the device or emulator and recording of user actions starts.
The recorded steps are shown in the test step table (as seen below)
If a test step is selected in the table the "Delete step" and "Take screenshot" buttons will be enabled.
1. Select any step in the table and click on "Delete step" to delete it.
2. Click "Take screenshot" to add a screenshot step after the selected step.
To stop the recording click "Stop Recording".
To save the test case click "Save", enter a test case name, and click "Ok".
If the test project already exists it will save the test case in that project. Otherwise it will first create the test project and then save the test case. Either start a new recording or close Robotium Recorder by clicking "Finish".
To see the saved test case(s) expand the test project and look in the src folder. The whole test project or a specific test case can be executed by right clicking it and selecting Run As > Android JUnit Test.
​
Credits,
My Parents - For the best support.
@Swaroop Bandagadde - For the best support.
Renas Reda(Founder of Robotium Test Automation Tool) - For liking my tutorial and for the best support.
My Other Works:
1. SELENIUM TEST AUTOMATION TOOL
2. MONKEYRUNNER TEST AUTOMATION TOOL

ROBOTIUM
1. Robotium​
Robotium is an open-source test framework for writing automated Black-box test cases for Android applications (Native/3rd party). With Robotium we can write function, system and acceptance test scenarios.
Robotium can be used both for testing of apps where source code is available and apps where only APK (Android Application Package) file is available and the implementation will be discussed in 4th chapter.
Robotium frame work released under Apache License 2.0. Its founder and main developer is Renas Reda. Latest Version of Robotium is 4.3.1(At the point of writing this book). The home page of Robotium is located under the following URL Robotium Home Page
Robotium extends the Android test framework to make it simpler to write tests. The main class for testing with Robotium is Solo.
Solo is initialized with the instrumentation of the test case and the first activity to test.
2. What all we need before we get it started?
We need the below:
1. Windows 7/8 OS
2. Java 6
3. Eclipse ADT
4. Android device running min android version 2.3.4*
5. Robotium Jar files (Robotium-solo-4.3.1.jar and Robotium-solo-4.3.1-javadoc.jar)
6. POI Jar files
7. Source code of the app to be tested*
*Are not mandatory.​
DOWNLOADS:
SimpleCalc app sourcecode: SimpleCalc
Robotium jar files : file1 and file2
POI jar files: POI.zip

How to setup Robotium using Eclipse ADT with source code of Android Application?
3. How to setup Robotium using Eclipse ADT with source code of Android Application?​
1.Open Eclipse ADT.
2.Import the source code of the application (to be tested) to eclipse.
3.I have given a source code which is written by me for testing purpose, you can find it here. [To import the project go to File ->Import -> select General -> Archive file -> Click on finish button]
4. Remove all the Errors as well as Lint warnings that might be present in the project by right clicking on the project (SimpleCalc) -> properties -> Android Lint Preferences -> Click on Ignore all button.
5. Create new Android Test project (Go to File -> New -> Other.. -> Select Android Test Project and give the project name as SimpleCalc-test). Details shown from the below screen shots:
NOTE: Select the option “An existing Android project” and select SimpleCalc project and click on Next button, this means you are going to test SimpleCalc app which is given by me.
6. Now right click on the empty package file that you get (Project_Name -> src -> Package) and select new Junit test case as show in below screen shot.
7. Now you will see a window where in you have to specify the Name of Junit test case as shown below (give it as TestCase_1):
8. Now you have to create new folder with name Robotium
9. Inside the Robotium folder paste the downloaded Robotium jar files.
10. Now go to Java Build Path by right clicking on the project -> properties and add the Robotium jar file as shown below:
11. Now click on the dropdown list of the Robotium jar file and select javadoc option as shown below:
12. Click on edit button and use the Robotium-solo-4.3.1-javadoc file as shown in the below screen shot:
13. Now go to Order and Export tab and click on select all button as shown below and click ok button:

Basic Android Test Project with Source Code
3a. Basic Android Test Project with Source Code​
1. Now your project will somewhat look like below:
2. Now we have to do some editing work to make this test case work as shown below:
package com.rhb.simplecalc.test;
import com.jayway.android.robotium.solo.Solo;
import com.rhb.simplecalc.MainActivity; // we have to import this class for testing our SimpleCalc application
import android.test.ActivityInstrumentationTestCase2; // You can run any test method on the UI thread
public class TestCase1 extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo; // solo is the main class of Robotium
public TestCase1() {
super(MainActivity.class); // Activity name of the class that you want to test.
// TODO Auto-generated constructor stub
}
@override
public void setUp() throws Exception {
solo = new Solo(getInstrumentation(), getActivity());
}
public void test() throws Exception{
// check that we have the right activity
solo.assertCurrentActivity("wrong activiy", MainActivity.class);
// enter the value “12” into first edit text
solo.enterText(0, "12");
// enter the value “2” into first edit text
solo.enterText(1, "2");
// Click on the first button
solo.clickOnButton(0);
// searchForText has a timeout of 5 seconds
assertTrue(solo.waitForText("24"));
}
@override
public void tearDown() throws Exception {
solo.finishOpenedActivities(); // finishes all opened activities
}
}
Click to expand...
Click to collapse
3. To Run the test just right click on the SimpleCalc-Test project -> Run As -> Android JUnit Test
4. Now you will see a tab of JUnit where in you will see your test results(Passed/Failed).
5. On the below Screen Shot I have shown you how the JUnit results are shown when the test is pass.
6. As you can see from the above screen shot clearly that our test is pass and the color indication is Green. If in case our test gets failed the color will be changed to Red as shown in below screen shot:
7. And the Fail reason will be shown at the Failure Trace as you can see from the above screen shot. Here I have purposely commented on the both edittext fields so that I can show you how the failed test case report will be.
8. Now the thing is how to take out the report? It’s easy, there are 3 ways of doing it they are:
8(a). By taking Logcat.
8(b). By Clicking on the Test Run History -> Export option you will get a xml file of the test report, and lastly.
8(c). Pushing the Test report to a text or excel file to the device.
9. Now we will see how to test the application when we don’t have source code with us in the next chapter.

How to setup Robotium using Eclipse ADT without source code of Android Application?
4. How to setup Robotium using Eclipse ADT without source code of Android Application?​
1. To get it started first let us see what is an apk file, why we need it? How to install it to a device?
2. Android application package file (APK) is the file format used to distribute and install application software and middleware onto Google's Android operating system. APK files are ZIP file formatted packages based on the JAR file format, with .apk file extensions.
3. We need apk file to test our application without having the source code. Now the question is from where do I get the apk file? It’s Easy just go to workspace of eclipse -> open the folder called SimpleCalc -> bin -> SimpleCalc.apk (~279KB).
4. To install SimpleCalc.apk file we are going to use a simple adb (Android Debug Bridge) command. The syntax for install an apk file is as below:
adb install [path of the apk file]
Click to expand...
Click to collapse
NOTE: Before Installing an apk file the important thing is to make sure that your device is in debugging mode and your device is connected to your Computer System. To enable debug mode in to your device go to Settings -> Developer options -> check mark Android debugging option.

Basic Android Test Project without source code
4a. Basic Android Test Project without source code​
1. Now as we are done with installing our apk file to device the next thing is very important, that is we have to create a new android test project so for this we have to keep at least one project open (It can be any project) and then only we can proceed else we will get an error saying which is show as below:
2. Now go to file -> new -> other -> Android Test Project -> give a name as SimpleCalcAPK-Test -> Select Test Target as “An existing Android project” -> Finish.
3. Now you will find a project with an empty package ready for creation of JUnit tests without source code.
4. Right click on the empty project -> new -> JUnit Test Case and give a name as ApkTestCase_1. Now you will see JUnit test case as below:
5. Now edit the above code as show below:
package com.rhb.simplecalc.test.test;
import com.jayway.android.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
public class ApkTestCase_1 extends ActivityInstrumentationTestCase2 {
public ApkTestCase_1() {
super(MainActivity);
// TODO Auto-generated constructor stub
}
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.rhb.Simplecalc.MainActivity";
private static Class MainActivity; // name of the activity class
static{
try {
MainActivity = Class
.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private Solo solo;
public void test() throws Exception{
solo.enterText(0, "12");
solo.enterText(1, "2");
solo.clickOnButton(0);
assertTrue(solo.waitForText("24"));
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
Click to expand...
Click to collapse
6. As soon as you Run this test you will get an Error saying “Process crashed” as shown below:
7. Solution for this is we have to just change the below lines from AndroidMenifest.xml file :
HTML:
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.rhb.simplecalc.test" />
Change it to:
HTML:
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.rhb.simplecalc" />
NOTE: The “targetPackage” will be the package called by the test which tests the functionality of the application in that called package.
8. Now copy paste the below code to test SimpleCalc application without source code:
package com.rhb.simplecalc.test.test;
import com.jayway.android.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
public class ApkTestCase_1 extends ActivityInstrumentationTestCase2 {
public ApkTestCase_1() throws ClassNotFoundException {
super(MainActivity);
// TODO Auto-generated constructor stub
}
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.rhb.simplecalc.MainActivity"; // name of the package with activity name here com.rhb.simplecalc is the package name and MainActivity is the activity name to be executed.
private static Class MainActivity; // name of the activity class
static{
try {
MainActivity = Class
.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
private Solo solo;
protected void setUp() throws Exception {
solo = new Solo(getInstrumentation(), getActivity());
}
public void test() throws Exception{
// solo.assertCurrentActivity("wrong activiy", MainActivity);
solo.enterText(0, "1");
solo.enterText(1, "2");
solo.clickOnButton(0);
assertTrue(solo.waitForText("2"));
}
protected void tearDown() throws Exception {
super.tearDown();
}
}
Click to expand...
Click to collapse
10. Now Run the project by right clicking on the project -> RunAs -> Android Junit Test and see the test results in the Junit tab.

What is JUnit Test Suite and why we need it in Robotium?
5. What is JUnit Test Suite and why we need it in Robotium?​
1.JUnit Test Suite is a collection of multiple unit tests each of which shall test the functionality of a Robotium script.
2.Android sdk comes built in with android jUnit which is different from the normal jUnit however the structure of android jUnit resembles that of regular JUnit. This is the reason why we need JUnit suit to call all the Robotium scripts and thereby used in android automation.
3.One JUnit suite shall call multiple activities of the application and therefore for bigger applications. It is possible to have multiple JUnit suits and we can further have a collection of these suites under a suite of suits(collection of individual JUnit suits).
4.Now we will write a simple JUnit test for our application which is as below:
As I said before normal JUnit Suite is different and android JUnit is different we have to do some modifications on the coding part to make JUnit suite work on android, which is as below:
package com.rhb.simplecalc.test.test;
import android.test.AndroidTestCase; // to make JUnitSuite work with android
public class JunitSuite extends AndroidTestCase {
@Override
public void setUp() throws Exception {
super.setUp();
}
// first JUnit Suite that will call ApkTestCase_1 class
public void Test() throws Exception {
ApkTestCase_1 a = new ApkTestCase_1();
a.setUp();
a.test();
a.tearDown();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
}
Click to expand...
Click to collapse
5.Now I will show you how to create Main Suite which intern calls all the subsuites which are present in the test project.
package com.rhb.simplecalc.test.test;
import junit.framework.Test;
import junit.framework.TestSuite;
public class MainSuite extends TestSuite {
public static Test suite () {
TestSuite suite = new TestSuite();
JunitSuite test = new JunitSuite();
test.setName("Suite1");
suite.addTest(test);
return suite;
}
}
Click to expand...
Click to collapse
6.Now as we are done with creating of JUnit Suite we will continue with creation of Data Driven testing in the next chapter.

How to Data-Drive Robotium Scripts?
6. How to Data-Drive Robotium Scripts? ​
1.We go for data driven testing when we have some modules that need to be tested for multiple values. For example in a application which has a login page with username and password field we have to test these edit text boxes for multiple inputs, it can be a number or it also can be a string or both together.
2.In our SimpleCalc application we have two edit text fields so we will see how to extract data from an Excel file and push the same to our application.
3.First we will create an excel file with some data present in it to test our application. (An Excel file for testing our app is attached here)
4.To extract data from Excel we use “FileInputStream” Class by which we can create/delete and modify a file.
5.Before we get it started some important things to be concentrated on are we have to keep the excel file inside the device and not on the PC because android Robotium doesn’t support the accessing of the files which are stored on to the computer system and not on the Device.
6.So first thing is to push the Excel file to the device. Just go to DDMS tab in eclipse and click on the push icon -> click on browse -> select the Test.xls file that I have provided. The screen shot for this is as shown below:
7.After pushing the Test.xls file to your device or Emulator the next thing what you have to do is add POI jar files to your build path. The link for these jar files can be found at first post.
8.Just create a new folder and name it as POI and add the Jar files to build path after adding them to build path it should look like below:
9.After successfully adding of the poi jar files its time to write program for accessing the data from excel file to our application.
10.The code for accessing data from excel file is as below:
public void test() throws Exception, IOException,
FileNotFoundException,InvalidFormatException {
String cellval1;
String cellval2;
FileInputStream fis= new FileInputStream(Environment.getExternalStorageDirectory() + "/Test.xls");
Workbook wb = WorkbookFactory.create(fis); // creates object for workbook Test.xls
Sheet ws = wb.getSheet("Sheet1"); // opens Sheet1 from workbook Test.xls
int rc = ws.getLastRowNum(); // counts the number of rows which are used
for(int i=1; i<=rc; i++)
{
Row r = ws.getRow(i); // ponts to the i'th ROW
for (int j=0;j==0;j++){
{
Cell c = r.getCell(j); // points to the j'th Column
cellval1=c.getStringCellValue(); // gets the data from J'th cell
Cell c1 = r.getCell(j+1); // ponts to the J+1'th column
cellval2=c1.getStringCellValue(); // gets the data from J+1'th cell
solo.clearEditText(0);
solo.enterText(0, cellval1); // pulls data from cellval1 and pushes it on to first editText box
solo.clearEditText(1);
solo.enterText(1, cellval2); // pulls data from cellval2 and pushes it on to second editText box
solo.clickOnButton(0);
}
}
}
}
Click to expand...
Click to collapse
11.Now when you run the code you will get the output as below:
12.Now as you can see from the above Screen Shot that the values from our excel sheet has been taken properly and after this the test should fail because we have given the second value as a special char and hence the test fails as shown below:
13.As we have finished with Data Driven Testing with Robotium we will now move with our last chapter where in we see what all issues I found while working with Robotium.

Issues with Robotium
7. Issues with Robotium
​
1. Reporting capability is limited to JUnit Reports in XML format.
2. Writing into excel or text file is a bit clumsy at present.
3. Identifying Excel file for script parameters is manual in nature (Pushing Excel files to the device manually using DDMS).
4. Data whether text or number is taken as a string and fed to the script.
5. No Option of Record and Playback ( Now available ).
6. Robotium doesn’t work with TestNG suite and Eclipse Kepler at present.
7. Robotium is dependent on Android JUnit for execution control.
***************************************************************************************************************************************************************************************

Very Clear from Basics
Excellent mix of concepts and practical explanation.

Swaroop Bandagadde said:
Excellent mix of concepts and practical explanation.
Click to expand...
Click to collapse
Thanks for guiding me.. !!:good::good:

Ravi H Basawa said:
7. Issues with Robotium
​
1. Reporting capability is limited to JUnit Reports in XML format.
2. writing into excel or text file is a bit clumsy at present.
3. Identifying Excel file for script parameters is manual in nature (Pushing Excel files to the device manually using DDMS).
4. Data whether text or number is taken as a string and fed to the script.
5. No Option of Record and Playback.
6. Robotium doesn’t work with TestNG suite and Eclipse Kepler at present.
7. Robotium is dependent on Android JUnit for execution control.
***************************************************************************************************************************************************************************************
Click to expand...
Click to collapse
A very Nice thread.. Rated 5 star

Rohit02 said:
A very Nice thread.. Rated 5 star
Click to expand...
Click to collapse
Thank you so much.. It means a lot to me.. :good:

Is it neccessary to have knowledge of android sdk before using robotium
hello,
I am doing poc on robotium can anybody help me in doing POC of some scenario's
1.app foreground background
2.lock and unlock device
3.kill app /restart app
4.network toggling

adityaroy612 said:
hello,
I am doing poc on robotium can anybody help me in doing POC of some scenario's
1.app foreground background
2.lock and unlock device
3.kill app /restart app
4.network toggling
Click to expand...
Click to collapse
Hi,
If you are using device and not emulator, Your device need to be rooted.
you have to pull settings.apk from the device and resign it back. Now write your script and run. It will work.
I am going to write a tutorial on testing of native apps with Robotium soon.
Thanks:good:

Related

[GUIDE] How To Install and Use Android SDK

{
"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"
}
*If you find this Guide Thread helpful, feel free to hit the "thanks" button below!​
What is Android SDK?
Everyone wants to program on Android; unfortunately, not everyone knows quite how to get started with their development environment. Google has put out both the Android SDK and the Android ADT in order to help developers integrate Android into their dev environment as well as facilitate more Android development. In this guide, we’ll take a look at how to set up a development environment for Android so you can start creating projects. Android SDK and Android ADT are essentials that you will need to include in your Android Developer Toolbox for use with many things, and can be a very powerful set of components from the simple, to the complicated. When it comes to Android modding, most novice users are confused or left wondering by reference over reference to a certain “adb”. This is specially true when you are looking up something on modding your device, or root it in particular. ADB is the wonder toy of Android and everyone seems to love it, so lets have a look at understanding what it is and why you need it, and how you can get it.​
What is ADT?
ADT (Android Developer Tools) is a plugin for Eclipse that provides a suite of tools that are integrated with the Eclipse IDE. It offers you access to many features that help you develop Android applications quickly. ADT provides GUI access to many of the command line SDK tools as well as a UI design tool for rapid prototyping, designing, and building of your application's user interface. Because ADT is a plugin for Eclipse, you get the functionality of a well-established IDE, along with Android-specific features that are bundled with ADT. The following describes important features of Eclipse and ADT:
Integrated Android project creation, building, packaging, installation, and debugging
ADT integrates many development workflow tasks into Eclipse, making it easy for you to rapidly develop and test your Android applications.
SDK Tools integration
Many of the SDK tools are integrated into Eclipse's menus, perspectives, or as a part of background processes ran by ADT.
Java programming language and XML editors
The Java programming language editor contains common IDE features such as compile time syntax checking, auto-completion, and integrated documentation for the Android framework APIs. ADT also provides custom XML editors that let you edit Android-specific XML files in a form-based UI. A graphical layout editor lets you design user interfaces with a drag and drop interface.
Integrated documentation for Android framework APIs
You can access documentation by hovering over classes, methods, or variables. ​
What is ADB?
ADB stands for Android Debug Bridge. It comes as a part of the standard Android SDK, which you can grab here in this guide. Basically, it provides a terminal-based interface for interacting with your phone’s file system. Since Android platform is based on Linux, command-line is sometimes the only way to obtain and manipulate root access often required to perform certain advanced operations on your device using root access. While these things can be done directly on the device itself using some terminal emulator, it will be rather difficult to execute complex commands on such a small screen. ADB provides the bridge between your machine and your computer.​
Preface: Dev Environment Notes:
Just a general rule to reduce headaches, if you're serious about Android development, your development machine should primarily be a development machine, as installation of other various programs may clutter it up and produce unexpected errors or other bizarre happenings. While this is rare, it’s not uncommon, and an exclusive development machine is recommended. If an extra machine is not available, a virtual machine used as a development machine works very well also. If this isn't an option either, you can always install Ubuntu 12.04 on your Windows PC and select whichever operating system you'd like at boot/reboot. The latter is my setup, since I run Windows 7 primarily, and Ubuntu for selected other functions -namely Android SDK. It's all your preference here, but keep in mind that if you start getting too deep in the rabbit hole with your Android development, you may want to consider a dedicated dev machine, or re-partition your Ubuntu setup to allow for more capabilities within it.​
Step 1: Install the JDK
Most of you probably have the Java JRE installed, but Android requires the JDK “Java Development Kit” to compile Java programs. The JDK is available on Oracle’s Java webpage. Install the version of the JDK appropriate for your OS; the Java EE 6 bundle is recommended, but you can install any bundle you like so long as it contains the JDK.
(Getting started on Ubuntu, see THIS PAGE)
Getting started on Windows:
Your download package is an executable file that starts an installer. The installer checks your machine for required tools, such as the proper Java SE Development Kit (JDK) and installs it if necessary. The installer then saves the Android SDK Tools into a default location (or you can specify the location). Make a note of the name and location of the SDK directory on your system—you will need to refer to the SDK directory later, when setting up the ADT plugin and when using the SDK tools from the command line. Once the tools are installed, the installer offers to start the Android SDK Manager. Start it and continue with the installation guide by clicking the Next link on the right. The Android SDK requires JDK version 5 or version 6. If you already have one of those installed, skip to the next step. In particular, Mac OS X comes with the JDK version 5 already installed, and many Linux distributions include a JDK. If the JDK is not installed, go to http://java.sun.com/javase/downloads and you'll see a list of Java products to download.
Linux users: Many Linux distributions come with an open source variant of the JDK, like OpenJDK or IcedTea. While you may be tempted to use these in support of open-source or for whatever reason, for maximum compatibility install the official Oracle JDK. You may choose to ignore this warning, but you may end up encountering obscure, strange errors because of it; if you do, most likely it’s some minor difference in the two JDKs.​
Step 2: Install Your IDE of Choice
You can by all means code straight up in Emacs or Vi; if you prefer doing that, this guide is not for you. For the rest of us, install a Java IDE; Eclipse is recommended as it is the IDE that the Android developers use and the IDE with official plugin support from Google. The rest of this guide will assume Eclipse is the IDE you’re using, but NetBeans has Android plugin support for it as well. When you download Eclipse, make sure to download Eclipse Classic or Eclipse for Java EE developers; there are quite a few flavors of Eclipse for download on their page, and you don’t want to end up with the C++ or PHP versions of Eclipse.
Obtain Eclipse
These alternatives may be available to obtain a copy of Eclipse for installation:
Download a current stable build of Eclipse from the Eclipse Web Site; note that the installation file is large (over 120 MB)
For the recommended package to download and install, click the link Eclipse IDE for Java EE Developers on the Eclipse Packages page. For the reason why this is the recommendation, see the following bullets:
There are a number of downloadable packages available, each a different "flavor" of Eclipse, which can be compared and contrasted from the Compared Eclipse Packages page. The recommended Eclipse package is the Eclipse IDE for Java EE Developers. This recommendation is made for those who develop in other languages / on other platforms as well, for the following reasons:
The "slimmer" Eclipse IDE for Java Developers lacks data tools, testing support, and parts of the Web Standard Tookit useful to all Java web application developers
The Eclipse Classic seems like it ought to be "slimmer" but in fact it is a larger download than the JEE package. Downloading and installing this package, then picking and choosing among additional packages described on the Eclipse Classic page is a viable alternative, but requires each developer to spend time researching the contents and utility of the multiple options.
Install Eclipse
There is no installer (executable program) used to install Eclipse. The process described below involves un-archiving (unzipping) a directory tree of files and placing it in an appropriate location on your hard disk. It is very strongly recommended that you locate the eclipse\ directory at the root of your computer's hard drive; or, minimally, on a directory path with no spaces in its name (e.g., C:\mystuff\eclipse\. It is worth noting that Eclipse does not write entries to the Windows registry; therefore, you can simply delete (or move) the installed files, shortcuts, and/or the workspace: there is no executable uninstaller either.
Unzip (or copy/unjar/check-out) the software into an appropriate location on your hard disk (e.g., C:\eclipse).
These instructions are written assuming that you are running eclipse from C:\eclipse; if you are using a different path, adjust accordingly.
Once the unzipped (copied/unjarred/checked-out) files are located on your filesystem, get started using Eclipse:
Run Eclipse by running C:\eclipse\eclipse.exe
The first time you run Eclipse, you will be prompted to identify a location for your Eclipse workspace. This is where local copies of your projects (files you check in and/or out of code repositories) will live on your file system. Do not create the workspace in a directory path that has spaces in it - i.e., not in the default C:\Documents and Settings\... directory presented by default on the first startup of Eclipse. Instead, it is recommended that your workspace be located at the root of your machine's hard disk, e.g., C:\workspace.
It is advisable to pass JVM arguments to Eclipse at startup to reserve a larger memory space for the IDE than the default. To, specify recommended JVM arguments, create a shortcut (probably on your desktop) with the following target (modified if you're using different directories):
Code:
C:\eclipse\eclipse.exe -jvmargs -Xms128m -Xmx512m -XX:MaxPermSize=128m
Step 3: Install the Android SDK
Now it’s time to install the Android SDK. You can grab it from the Android Developer website at:
http://developer.android.com/sdk/index.html​
Download the installer for your particular operating system, and open it up when you’re done:
Android SDK Manager
The Android SDK Manager is modular, meaning that you download the initial package and then download separate packages within the framework in order to provide more functionality. This lets the SDK be more flexible, as you don’t need to keep downloading entire packages every time a new version comes out; you can simply download the latest module and pop it into the SDK. You can pick and choose which modules to install, but if you’ve got the hard drive space I recommend installing all of the different flavors of Android; it will help later when debugging apps, especially on older Android OSes.​
Step 4: Install the Android ADT for Eclipse
NOTE: if you’re using NetBeans, you want the nbandroid plugin, found here:
http://kenai.com/projects/nbandroid/pages/install​
Now that the SDK is installed, you should install the Android ADT plugin. It’s not strictly necessary to do so, but the ADT offers powerful integration with many of the Android tools, including the SDK Manager, the AVD Manager, and DDMS, or dynamic debugging. All of these are extremely useful to have when creating an Android application, and if you want to skip them you should do so at your own peril!​
Eclipse ADT Plugin
To install the ADT, you’re going to have to add a custom software package to Eclipse. To do so, head over to the “Help” button on Eclipse’s menu and click the “Install New Software” button. Click “Available Software”, click “Add Remote Site”, and pop in this URL:
https://dl-ssl.google.com/android/eclipse/​
Eclipse ADT Install
Occasionally, for whatever reason, some people have trouble downloading the ADT from that secure site. If you’re having issues downloading the ADT, simply remove the “s” off the end of the “https”, and the download should work as intended. Once that’s done, head back over to the Available Software tab and check the boxes for Developer Tools, Android DDMS, and Android Development Tools; again, none of these are mandatory, but they’re all going to be very useful later on. The packages will take a bit to download; once they’re done, restart Eclipse!​
Step 5: Create an Android Virtual Device (or AVD)
Like the previous step, this step isn’t entirely necessary; you could do all your debugging and development work on an actual Android handset. Creating AVDs is a great way to see how your application might work across different operating systems and handset types, as AVDs can mimic not only different Android OSes but also different hardware; you can change such settings as heap size, display type, and maximum memory, making it useful to try and figure out where bugs are happening when you don’t own a multitude of different handsets to test on! To create an AVD, you can open the Android AVD manager from Eclipse from the “Window” button on the top bar, and go to “Virtual Devices”. From there, you can add, configure and delete them:
Android Virtual Device (AVD) Manager
NOTE: This isn’t IDE specific. For those of you running a different IDE, the AVD Manager can be accessed in the same manner as the Android SDK is accessed outside of Eclipse; this is just a very easy shortcut for those with the Android ADT installed. Need More Help? Try this 30-minute video put together by Guy Cole, that walks you through the complete step-by-step setup.​
So, You've Installed Android SDK, Now What?
The Android platform provides support for both speech recognition and speech synthesis. In this tutorial, we will create a simple Android app which allows the user to speak, attempts to recognize what they say, and then repeats what was recognized back to them using the Text To Speech engine.
Step 1: Start an Android Project​
Create a new Android project in Eclipse. Alternatively, if you want to implement the speech recognition functionality in an existing app, open it instead. For this tutorial we have a minimum SDK version of 8, and you do not need to make any particular additions to your Manifest file, the default contents should suffice.
Step 2: Define the User Interface​
Let’s start by defining the user interface. When the app launches, the user will be presented with a button. On pressing the button, the app will prompt them to speak, listening for their voice input. When the speech recognition utility processes the speech input, the app will present a list of suggested words to the user. As you’ll know if you’ve tried speech recognition as a user, the recognizer is not always accurate, so this list is essential. When the user selects an item from the list, the app will speak it back to them using the TTS engine. The TTS part of the application is optional, so you can omit it if you prefer.
The app is going to use a few text Strings as part of the interface, so define them by opening the “res/values/strings.xml” file and entering the following content:
Code:
<resources>
<string name="intro">Press the button to speak!</string>
<string name="app_name">SpeechRepeat</string>
<string name="speech">Speak now!</string>
<string name="word_intro">Suggested words…</string>
</resources>
Of course, you can alter the String content in any way you like.
Open your “res/layout/main.xml” file to create the main app layout. Switch to the XML editor if the graphical editor is displayed by default. Enter a Linear Layout as the main layout for the app’s launch Activity:
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
androidrientation="vertical"
android:background="#ff330066"
androidaddingBottom="5dp" >
</LinearLayout>
The Linear Layout contains various style declarations including a background color. Inside the Linear Layout, first enter an informative Text View:
Code:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/intro"
androidadding="5dp"
android:textStyle="bold"
android:textSize="16dp"
android:gravity="center"
android:textColor="#ffffff33" />
Notice that the Text View refers to one of the Strings we defined. It also sets various display properties which you can alter if you wish. After the Text View, add a button:
Code:
<Button android:id="@+id/speech_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/speech" />
The user will press this button in order to speak. We give the button an ID so that we can identify it in the Java code and display one of the Strings we defined on it. After the button, add another informative Text View, which will precede the list of suggested words:
Code:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
androidadding="5dp"
android:text="@string/word_intro"
android:textStyle="italic" />
Again, this Text View uses a String resource and contains style properties. The last item in our main.xml Linear Layout is the list of suggested words:
Code:
<ListView android:id="@+id/word_list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
androidaddingLeft="10dp"
androidaddingTop="3dp"
androidaddingRight="10dp"
androidaddingBottom="3dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="@drawable/words_bg" />
The List View will be populated with data when the app runs, so we give it an ID for identification in Java. The element also refers to a drawable resource, which you should add to each of the drawables folders in your app’s “res” directory, saving it as “words_bg.xml” and entering the following content:
Code:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:dither="true">
<gradient
android:startColor="#ff000000"
android:endColor="#ff000000"
android:centerColor="#00000000"
android:angle="180" />
<corners android:radius="10dp" />
<stroke
android:width="2dp"
android:color="#66ffffff" />
</shape>
This is a simple shape drawable to display behind the List View. You can of course alter this and the List View style properties if you wish. The only remaining user interface item we need to define now is the layout for a single item within the list, each of which will display a word suggestion. Create a new file in “res/layout” named “word.xml”and then enter the following code:
Code:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
androidadding="5dp"
android:textColor="#ffffffff"
android:textSize="16dp" >
</TextView>
Each item in the list will be a simple Text View. That’s our interface design complete. This is how the app appears on initial launch:
Step 3: Setup Speech Recognition​
Now we can implement our Java code. Open your app’s main Activity and add the following import statements at the top:
Code:
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
You may not need all of these if you do not implement the TTS functionality – Eclipse should highlight imports you have not used so check them when you finish coding. Extend your opening class declaration line as follows, altering the Activity name to suit your own:
Code:
public class SpeechRepeatActivity extends Activity implements OnClickListener, OnInitListener {
The “OnInitListener” is only required for the TTS function. Add the following instance variables inside your class declaration, before the “onCreate” method:
Code:
//voice recognition and general variables
//variable for checking Voice Recognition support on user device
private static final int VR_REQUEST = 999;
//ListView for displaying suggested words
private ListView wordList;
//Log tag for output information
private final String LOG_TAG = "SpeechRepeatActivity";//***enter your own tag here***
//TTS variables
//variable for checking TTS engine data on user device
private int MY_DATA_CHECK_CODE = 0;
//Text To Speech instance
private TextToSpeech repeatTTS;
Inside your “onCreate” method, your class should already be calling the superclass method and setting your main layout. If not, it should begin like this:
Code:
//call superclass
super.onCreate(savedInstanceState);
//set content view
setContentView(R.layout.main);
Next, still inside your “onCreate” method, retrieve a reference to the speech button and list we created, using their ID values:
Code:
//gain reference to speak button
Button speechBtn = (Button) findViewById(R.id.speech_btn);
//gain reference to word list
wordList = (ListView) findViewById(R.id.word_list);
The List View is an instance variable, accessible throughout the class. Now we need to find out whether the user device has speech recognition support:
Code:
//find out whether speech recognition is supported
PackageManager packManager = getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (intActivities.size() != 0) {
//speech recognition is supported - detect user button clicks
speechBtn.setOnClickListener(this);
}
else
{
//speech recognition not supported, disable button and output message
speechBtn.setEnabled(false);
Toast.makeText(this, "Oops - Speech recognition not supported!", Toast.LENGTH_LONG).show();
}
We query the environment to see if the Recognizer Intent is present. If it is, we instruct the app to listen for the user pressing the speech button. If speech recognition is not supported, we simply disable the button and output an informative message to the user.
Step 4: Listen for Speech Input​
Let’s setup the click listener for the speech button we’ve instructed the app to detect clicks for. Outside the “onCreate” method, but inside your Activity class declaration, add an “onClick” method as follows:
Code:
/**
* Called when the user presses the speak button
*/
public void onClick(View v) {
if (v.getId() == R.id.speech_btn) {
//listen for results
listenToSpeech();
}
}
Now implement the method we’ve called here after the “onClick” method:
Code:
/**
* Instruct the app to listen for user speech input
*/
private void listenToSpeech() {
//start the speech recognition intent passing required data
Intent listenIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//indicate package
listenIntent.putExtra(RecognizerIntent.EXTRA_CALLI NG_PACKAGE, getClass().getPackage().getName());
//message to display while listening
listenIntent.putExtra(RecognizerIntent.EXTRA_PROMP T, "Say a word!");
//set speech model
listenIntent.putExtra(RecognizerIntent.EXTRA_LANGU AGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//specify number of results to retrieve
listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_R ESULTS, 10);
//start listening
startActivityForResult(listenIntent, VR_REQUEST);
}
Some of this code is standard for setting up the speech recognition listening functionality. Areas to pay particular attention to include the line in which we specify the “EXTRA_PROMPT” – you can alter this to include text you want to appear for prompting the user to speak. Also notice the “EXTRA_MAX_RESULTS” line, in which we specify how many suggestions we want the recognizer to return when the user speaks. Since we are calling the “startActivityForResult” method, we will handle the recognizer results in the “onActivityResult” method.
When the app is listening for user speech, it will appear as follows:
Step 5: Present Word Suggestions​
Implement the “onActivityResult” method inside your class declaration as follows:
Code:
/**
* onActivityResults handles:
* - retrieving results of speech recognition listening
* - retrieving result of TTS data check
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//check speech recognition result
if (requestCode == VR_REQUEST && resultCode == RESULT_OK)
{
//store the returned word list as an ArrayList
ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTR A_RESULTS);
//set the retrieved list to display in the ListView using an ArrayAdapter
wordList.setAdapter(new ArrayAdapter<String> (this, R.layout.word, suggestedWords));
}
//tss code here
//call superclass method
super.onActivityResult(requestCode, resultCode, data);
}
Here we retrieve the result of the speech recognition process. Notice that the “if” statement checks to see if the request code is the variable we passed when calling “startActivityForResult”, in which case we know this method is being called as a result of the listening Intent. The recognizer returns the list of 10 suggested words, which we store as an Array List. We then populate the List View with these words, by setting an Array Adapter object as Adapter for the View. Now each of the items in the List View will display one of the suggested words.
If the app successfully recognizes the user input speech and returns the list of words, it will appear as follows:
Alternatively, if the app does not recognize the user speech input, the following screen will appear:
Step 6: Detect User Word Choices​
We want to detect the user selecting words from the list, so let’s implement a click listener for the list items. Back in your “onCreate” method, after the existing code, set the listener for each item in the list as follows:
Code:
//detect user clicks of suggested words
wordList.setOnItemClickListener(new OnItemClickListener() {
//click listener for items within list
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//cast the view
TextView wordView = (TextView)view;
//retrieve the chosen word
String wordChosen = (String) wordView.getText();
//output for debugging
Log.v(LOG_TAG, "chosen: "+wordChosen);
//output Toast message
Toast.makeText(SpeechRepeatActivity.this, "You said: "+wordChosen, Toast.LENGTH_SHORT).show();//**alter for your Activity name***
}
});
We use the “setOnItemClickListener” method to assign a listener to each item in the list. Inside the new “OnItemClickListener”, we implement the “onItemClick” method to respond to these clicks – this method will fire when the user selects a suggested word from the list. First, we cast the View that has been clicked to a Text View, then we retrieve the text from it. This text is the word the user has selected. We write the chosen word out to the Log for testing and output it back to the user as a Toast message. Depending on the needs of your own application, you may wish to carry out further processing on the chosen word – this code is purely for demonstration.
The user can press the touchscreen or use a trackball to select words in the list.
When the user selects a word, the Toast message appears confirming it.
Step 7: Setup TTS Functionality​
If you do not want to implement the Text To Speech functionality, you can stop now and test your app. We only require a little more processing to make our app repeat the user’s chosen word. First, to set up the TTS engine, add the following code to the section in your “onCreate” method where you queried the system for speech recognition support. Inside the “if” statement, after “speechBtn.setOnClickListener(this);”:
Code:
//prepare the TTS to repeat chosen words
Intent checkTTSIntent = new Intent();
//check TTS data
checkTTSIntent.setAction(TextToSpeech.Engine.ACTIO N_CHECK_TTS_DATA);
//start the checking Intent - will retrieve result in onActivityResult
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
Like the speech listening process, we will receive the result of this code checking for TTS data in the “onActivityResult” method. In that method, before the line in which we call the superclass “onActivityResult” method, add the following:
Code:
//returned from TTS data check
if (requestCode == MY_DATA_CHECK_CODE)
{
//we have the data - create a TTS instance
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
repeatTTS = new TextToSpeech(this, this);
//data not installed, prompt the user to install it
else
{
//intent will take user to TTS download page in Google Play
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACT ION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
Here we initialize the TTS if the data is already installed, otherwise we prompt the user to install it. For additional guidance on using the TTS engine, see the Android SDK: Using the Text to Speech Engine tutorial.
To complete TTS setup, add the “onInit” method to your class declaration, handling initialization of the TTS as follows:
Code:
/**
* onInit fires when TTS initializes
*/
public void onInit(int initStatus) {
//if successful, set locale
if (initStatus == TextToSpeech.SUCCESS)
repeatTTS.setLanguage(Locale.UK);//***choose your own locale here***
}
Here we simply set the Locale for the TTS, but you can carry out other setup tasks if you like.
Step 8: Repeat the User Choice​
Finally, we can repeat the user’s chosen word. Back in your “onCreate” method, inside the “OnItemClickListener” “onItemClick” method, after the line in which we output a Toast message, add the following:
Code:
//speak the word using the TTS
repeatTTS.speak("You said: "+wordChosen, TextToSpeech.QUEUE_FLUSH, null);
This will cause the app to repeat the user’s chosen word as part of a simple phrase. This will occur at the same time the Toast message appears.
Conclusion
That’s our complete Speak and Repeat app. Test it on an Android device with speech recognition and TTS support – the emulator does not support speech recognition so you need to test this functionality on an actual device. The source code is attached, so you can check if you have everything in the right place. Of course, your own apps may implement speech recognition as part of other processing, but this tutorial should have equipped you with the essentials of supporting speech input.​
Android SDK Commands & Explanations
Adb has many built in commands. Some are interactive (meaning they keep running until you stop them) and some just perform a simple task. Below is a list of the commands in the 1.0 SDK version of adb.​
Android Debug Bridge version 1.0.20
Code:
-d - directs command to the only connected USB device
returns an error if more than one USB device is present.
-e - directs command to the only running emulator.
returns an error if more than one emulator is running.
-s <serial number> - directs command to the USB device or emulator with
the given serial number
-p <product name or path> - simple product name like 'sooner', or
a relative/absolute path to a product
out directory like 'out/target/product/sooner'.
If -p is not specified, the ANDROID_PRODUCT_OUT
environment variable is used, which must
be an absolute path.
devices - list all connected devices
device commands:
adb push <local> <remote> - copy file/dir to device
adb pull <remote> <local> - copy file/dir from device
adb sync [ <directory> ] - copy host->device only if changed
(see 'adb help all')
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-l] [-r] <file> - push this package file to the device and install it
('-l' means forward-lock the app)
('-r' means reinstall the app, keeping its data)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.
adb help - show this help message
adb version - show version num
DATAOPTS:
(no option) - don't touch the data partition
-w - wipe the data partition
-d - flash the data partition
scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-product - prints: <product-id>
adb get-serialno - prints: <serial-number>
adb status-window - continuously print device status for a specified device
adb remount - remounts the /system partition on the device read-write
networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PDP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, both /system and /data partitions will be updated.
- If it is "system" or "data", only the corresponding partition
is updated.
Common Use:​
Some of the more common commands in adb are push, pull, shell, install, remount, and logcat.
Push sends a file from your desktop computer to your Android device:
Code:
adb push test.txt /sdcard/test.txt
Pull pulls a file from your Android device to your desktop computer:
Code:
adb pull /sdcard/test.txt test.txt
Shell lets you run an interactive shell (command prompt) on the Android device:
Code:
adb shell
Install lets you install an android APK file to your Android device:
Code:
adb install myapp.apk
Remount remounts the /system partition as writable (or readonly if it is already writeable):
Code:
adb remount
Logcat lets you view the devices debug logs in real time (must press control+c to exit):
Code:
adb logcat
Further Notes On This Subject
It's great to see guides like these. I think every device forum should have these stickied in their general section. We all have/had to start somewhere. Having nice guides with accurate up-to-date information is only going to benefit everyone, and makes learning and understanding much easier. Fact is, we're all here for the same reason, to capitalize on the potential our devices have, and enjoy them. So, thanks for putting this together. It might seem trivial to a lot of the more experienced people, but those who aren't will definitely appreciate it.
Thanks. This is helpful.
Sent from my MB865
Hey Apex great job on the guide
I just wish this was here the first time I installed the the android sdk
I'm sure it will be useful to alot of members
41rw4lk said:
I think every device forum should have these stickied in their general section.
Click to expand...
Click to collapse
+1
Sticky?
Speak only when it improves on your silence.
Sorry for OT, this is not for Atrix 2 but I have question :
I want to extract included kernel in CM9 Rom, it is inside boot.img file. I've used Android Kitchen for extracting, it's ok now. I had zImage file.
So now how can I build flash-able zip file for CWM ? Tried UpdateZipCreator program but it showed error (7) when flashing.
I just wanna test many difference kernels and then come back to original but no flashable CM9 kernel here on xda.
vinamilk said:
Sorry for OT, this is not for Atrix 2 but I have question :
I want to extract included kernel in CM9 Rom, it is inside boot.img file. I've used Android Kitchen for extracting, it's ok now. I had zImage file.
So now how can I build flash-able zip file for CWM ? Tried UpdateZipCreator program but it showed error (7) when flashing.
I just wanna test many difference kernels and then come back to original but no flashable CM9 kernel here on xda.
Click to expand...
Click to collapse
Okay, Jim will probably be the one to ask on this. I don't recall which device you have currently (viewing from my phone) but he's the one who wrote the kernel for CM9 on the SGS3. I'm assuming you want to run the CM9 rom with 'experimental' kernels, so I'd PM him and ask (Sorry Jim, lol) but I'm not the expert on kernels or Android Kitchen, least not as knowledgeable as I should be to give a suitable answer...
Sent from my SAMSUNG-SGH-I747 using xda premium
oh! thanks a lot! I am very happy to find this!
long long ago! I start to find this resourse :cyclops:
EXCELLENT! I don't know i didn't see this before. Maybe because i didn't have this phone in August i think.
But great, tomorrow i will see if i can combine one of my designs with this, and try to make an alpha app.
Good guide
Hit thnx for every help
I just wanted to obtain logcat but where to type adb logcat...I get this in sdk
luvk1412 said:
I just wanted to obtain logcat but where to type adb logcat...I get this in sdk
Click to expand...
Click to collapse
With the sdk.. go to android-sdk/tools/ folder and double-click monitor.bat - easiest/nicest way to watch the logs..
To set up adb to be used from the command prompt or terminal, make sure you set your environment variables (or your .bashrc in Linux) to the path of adb in the sdk (it's in platform-tools)..
For Windows (Win7 example): Go to Start> right-click Computer>Properties>Advanced System Settings>Environment Variables...
Look under System Variables to see if you somehow have the path to C:\android-sdk\platform-tools in there already (or your specific location - just don't use spaces in the folder names in your path). If not, click on PATH under System Variables and Edit it..
Add your path to adb.exe (C:\android-sdk\platform-tools, for exapmle) to the end of the string of paths there. You can also add the path to \android-sdk\tools for good measure..
Click OK.. "Revenge of the Fern" - inside joke...
For Linux (Ubuntu 12.04, for example): Go to your home folder, hit Ctrl+H, open the .bashrc, and add this (or your specific path) to the bottom:
Code:
# Android tools
export PATH=${PATH}:~/android-sdk/tools
export PATH=${PATH}:~/android-sdk/platform-tools
Then you should be able to open the command prompt or terminal and type: adb devices - and hopefully get your device id..
Then: adb logcat - for logcat (or just use the monitor.bat as mentioned above, it has a much nicer interface)
See my "Guide" on getting started in the Themes&Apps section for more adb stuff too..
Other alternatives for logcat directly on your phone are through Terminal Emulator (type su.. then logcat), or apps available on the Play Store (aLogcat, for example).
Hey I am just getting started with android dev. Have done just a few tutorials from the developers.android.com, so basically a noob at this. But I saw that Google recently launched the android studio for app developement. I was just getting started with eclipse, but the android studio looks more intuitive because of its better GUI. I'm bad at xml editing too So I think the interface of Android Studio would suit better. Is there anyone here who has tried both and knows the cons of abandoning eclipse IDE and going for Android Studio?
help
Hay friend i have downloaded Java JDK 6.0.45 & 6.0.07 & Java JRE 6,7 to But when i open eclips it shows me this error can you help me to get it solve
http://forum.xda-developers.com/showthread.php?t=2276871
http://forum.xda-developers.com/showthread.php?t=2227376&page=14
Do you know what path i use to upack the adt bundle i have unpacked it in almost every location on my computer and still nothing eclipes wont work nothing works plz let me know if you can help i really dont want to smash my new laptop that will be no2 in amonth if i do plz help

[APP][DEV][16/10-1.0][29/11-2.0-BETA] BuildBox [Rom-Kitchen/Ota][4.0+]

BuildBox
The main intend of this application is to provide an easy to use, but powerful way to serve updates and addons for developers to their users, but it doesn't stop there, it also can be used by the user itself as batch flashing tool for files on the internal or external sd (openrecoveryscript supporting recovery and root are prerequisite).
But please keep in mind, this is still beta stage, so far all is stable, but the code itself needs refactoring still and some additional features i want to add are still missing, also the included images are far from being great.
Why i built this?
Most of the current alternatives public available seemed not as powerful as they could be, because of the fact that they are closed source i started to build something similar myself from scratch.
What does it serve?
Tabbed UI
Nested lists within the tabs (in theory infinite levels of nesting [but for usability i wouldn't recommend more than 5 steps])
Detail views with many optional fields, like description, changelog, developers, images,...
Completely remotly configured content using json
Optional Md5 verfification
Download queue
Changelist of added, removed, updated & downgraded items
Sorting of download queue by drag & drop
Concurrent downloads to achieve full use of bandwidth (configurable amount)
Backup and restore of download queues
Support of every host with direct link capabilities
Support of hosts with up to 5 redirects (note: still direct link redirects, download webpages don't get handled)
Internal retry or resume (if supported by the server) functionality to avoid broken downloads because of unstable connections (up to 5 retries)
Direct install of apks
"External" link handling
Direct flash capabilities (if an openrecoveryscript supporting recovery is installed)
Adding of zips from storage to the queue
Backup/wipe options before flashing
Queue filter to only flash Successful/Done (Successful=downloaded+md5sum correct, Done=donwloaded+no md5sum provided) downloads (md5mismatches can optional be taken in as well)
OTA updates
Configurable interval for update check
Update version filter to avoid multiple notifications per version
New version check on startup
Image recycling and scaling (if an image is used more than once [identified by it's url], it will be downloaded only once and simply reused, also it will be scaled to the fitting size of the view to take as less bandwidth and ram as possible)
more to come...
Why json and not xml?
Xml is pretty good for local configuration, but json is the way to go when it comes to remote content.
It is highly mutable, lightweight and easy to use. Also the possibility for typos and errors is much less than with xml, because simple brackets and key value pairs are used instead of tags.
Last but not least, json files are about half of the sice of xml files if the same content is provided and the possible use of a webservice to provide it is pretty simple.
How to use as rom developer?
The application uses build.prop properties to configure rom update url, content url, rom version and default download directoy.
For update and content url there are also string resources present (to be able to publish the app to the play store to provide the rom itself with it e.g.).
All of this properties are optional (if they are not provided default values are taken).
Build.prop sample
Code:
buildbox.downloaddir=/storage/sdcard0/TestRom
buildbox.version=1.0.3c1
buildbox.updateurl=http://www.test.com/Rom.json
buildbox.contenturl=http://www.test.com/Content.json
Common content description
At the content json all root items will be shown as tabs, everything inside them are listitems.
Every item containing another list of items must contain the "children" property.
Every item containing a detail item must contain the "detail" property instead.
Key Value pair description
Common properties:
Code:
"title": "some value" -> this is the title of the chapter/listitem/detailitem (depends on the item type) (if the detailview doesn't contain a title property it will be taken from it's parent)
"device": "GT-I9300" -> this value is used to filter content which is only available for specific devices, it is compared with the ro.product.model build.prop property (because it is almost untouched by moders)
"thumbnailurl": "some url" -> this is the thumbnail shown at a listitem, it will be loaded asynchronous
"children": [ { some child items } ] -> this property is used to identify that this item contains another list
"detail" : { some detail properties } -> this property is used to identify this item as last item before a detail view is shown
Additional detail properties:
Code:
"version": "some version" -> sets the version (must not be inside the detail item, can also be inside his parent)
"description": "some text" -> sets the description (basic html notation can be used for formating)
"type": "zip" -> possible values are zip, apk, web, other, this will override the basic behaviour of parsing the mime type and will directly threaten it as the provided type [if external is used and the url property is given the url property will be taken for opening instead of the first webpages link])
"md5": "a md5sum" -> sets the md5sum of the package (only used for download verification if provided)
"url": "some url" -> the url where the item can be downloaded from
"webpages": [ "some url",
"some other url",
....
] -> if no url provided the first item of this array will be taken as external link, but in common provided as hyperlinks on the detail view to support pages
"images": [ "some url",
"some other url",
....
] -> used to show screenshots,... within the detail view (also loaded asynchronous)
"changelog": [ "a change",
"another change",
......
] -> to show a changelog, also supports html notation
"developers": [ { "some developer name": "" },
{ "another developer name": "some donation or profile page" },
......
] -> used to show the realted developers, if a donation or profile url is given the name will be shown as hyperlink, if it's empty as plain text
Server File Samples
Content.json:
Code:
[{
"title":"Apps",
"device":"GT-I9300", [B]//optional, compared with the ro.product.model build.prop property, to shows items for specific devices only (can be put at every level inside the nesting of an item, except inside a detail item)[/B]
"thumbnailurl":"http://ms-team-hd.tectas.eu/images/Apps.png",
"children": [
{"title":"4.2 Camera/Gallery",
"detail":
{"description":"Aosp Camera from android 4.2 with sphere photo feature",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Apps/4.2Camera_App.zip",
"md5":"10cfc3983156d42a9dbafe7bc8265257"
}
},
{"title":"4.2 Clock",
"detail": {
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Apps/4.2-Clock_App.zip",
"md5":"8334f1ed2ec79efbe4199a86fda7ee58"
}
},
{"title":"4.2 Keyboard",
"detail": {
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Apps/4.2Keyboard_App.zip",
"md5":"de0d134795217b21ccbeb0f1b7dd3cdd"
}
}
]
},{
"title":"Bloat",
"thumbnailurl":"http://ms-team-hd.tectas.eu/images/Bloat.png",
"children": [
{"title":"Calculator",
"detail":
{"webpages": [
"http://ms-team-hd.tectas.eu/download.php?file=Addons/Bloat/Calculator_App.zip"
],
"md5":"6adbc0077f7aac1f25ed584cff5c4d0e"
}
},
{"title":"SPlanner",
"detail": {
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Bloat/SPlanner_App.zip",
"md5":"2949654d704a59cdbd17b7227b825d37"
}
}
]
},{
"title":"Themes",
"thumbnailurl":"http://ms-team-hd.tectas.eu/images/Themes.png",
"children": [{
"title":"Battery Mods",
"thumbnailurl":"http://ms-team-hd.tectas.eu/images/Battery.png",
"children": [
{"title":"Blue Battery",
"thumbnailurl":"http://ms-team-hd.tectas.eu/Addons/Battery/Images/BlueBattery.png",
"detail":
{"description":"Stock battery icon in blue made by raubkatze",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Battery/BlueBattery_Mod.zip",
"md5":"f1bc5f90dc284df34fb0c8d2d9044330"
}
},
{"title":"Blue Battery Percentage",
"thumbnailurl":"http://ms-team-hd.tectas.eu/Addons/Battery/Images/BlueBatteryPercentage.png",
"detail": {
"description":"Stock battery icon in blue with percentage made by thisiskindacrap",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Battery/BlueBatteryPercentage_Mod.zip"
}
},
{"title":"Blue Battery Circle",
"thumbnailurl":"http://ms-team-hd.tectas.eu/Addons/Battery/Images/BlueCircle.png",
"detail": {
"description":"Blue circle battericon with percentage in the center made by raubkatze",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Battery/BlueCircle_Mod.apk", //apk extension will be read and the install dialog will pop up
"md5":"c43c2734846ced3db5ed5987d5647bae"
}
}
]
},{
"title":"Framework Themes",
"thumbnailurl":"http://ms-team-hd.tectas.eu/images/Apps.png",
"children": [{
"title":"Elegant Theme",
"detail": {
"describtion":"Eye-Candy Theme by ThilinaC",
"url":"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=0B8AYcerB14i3YVBmTEM4b0tzOVU",
"md5":"5e0d5a4578f01cfa8b357e79193f070b"
}
},{
"title":"MS Team Blackbean Theme",
"detail": {
"description":"Black and white theme made by alvin551",
"url":"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=0B8AYcerB14i3VmUwWTVKdWZ6UWM",
"md5":"93442e1fb4197e554ebdb1c8ff9c52a1"
}
},{
"title":"MS Team HD Theme",
"detail": {
"description":"Holo style theme. The theme is not originally created by MS Team HD, it uses parts of many other themes. All credits to the creators of the themes this is based on.",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Themes/MS-Team-HD_Theme.zip",
"md5":"15eec7c80db7acbaccd939f827d806e9"
}
}
]
},{
"title":"Multiwondow Themes",
"children": [{
"title":"Multiwindow Blackbean",
"detail": {
"description":"Multiwindow theme made by alvin551",
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Themes/Flashbar-BlackBean_Mod.zip",
"md5":"4be1c0da1d77121de9627dd2570fee00"
}
},{
"title":"Multiwindow Black Glass",
"detail": {
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Themes/Flashbar-Glass-Black_Mod.zip",
"md5":"b8befba0558fdd954c8c73563761565c"
}
},{
"title":"Multiwindow Blue Glass",
"detail": {
"url":"http://ms-team-hd.tectas.eu/download.php?file=Addons/Themes/Flashbar-Glass-Blue_Mod.zip",
"md5":"d98c0cd04fc3240b372a78911a09c865"
}
}
]
}
]
}
]
Rom.json (which contains basically nothing less than a detailitem, means all optional properties used here can also be used at detail items within the Content.json):
Code:
{
"title": "MS Team HD", [B]//optional if parent item is present[/B]
"version": "9.0.1", [B]//optional[/B]
"description": "test", [B]//optional[/B]
"type": "zip", [B]//optional[/B]
"md5": "75a3a73d3ac941cc83f90dd80d000477", [B]//optional[/B]
"url": "http://ms-team-hd.tectas.eu/download.php?file=Rom/MS-Team-HD_9.0.1_XXEMA2.7z", [B]//optional[/B]
"webpages" : [
"http://forum.xda-developers.com/showthread.php?t=1886332",
"http://ms-team-hd.tectas.eu"
], [B]//optional[/B]
"images": [
"http://ms-team-hd.tectas.eu/Winscp-Screenshot.png"
], [B] //optional[/B]
"changelog": [
"change1",
"change2"
], [B]//optional[/B]
"developers": [
{ "tester": "" },
{ "tester2": "http://test" }
] [B]//optional[/B]
}
NOTE: if you simply want to take and alter this examples, remove the comments (everthing starting with //) they are not supported within json.
Is it open source?
Yes, the java packges are licensed under lgpl, which means they can be integrated within every other application without publishing the source, only if the code inside the packages themself is altered the code has to be published. I have chosen this approach in the open sense of android, everyone is allowed to fork/clone my github repository and do whatever he likes with the code, i just want possible fixes or enhancements to be public available for everyone (also fell free to send me pull requests if you like), that's at least my view of what open source means, all should work together to make the best out of something, if they like to, otherwise, take what is already served or find someone able to do the needed changes.
Wait, two repositories? Why the hell...
Well, it's pretty simple, the library part already includes everything which is needed to get the work done, except of one thing, the main activity. It "only" includes an generic abstract activity which serves the fitting implementations to get it's job done without taking into account how the main activity is build up (be it tabed, with lists or whatever). To make your own UI set up on this activity it serves abstract methods you have to implement to handle e.g. viewing the download queue, updating it while downloading,...
But that's as well only a nice to have and should give you more possibilities if you want to use them, if your fine with the tabed UI I built, simply take the application repository, override the resources you like (if you want to) and your already done. I also splitted it up for easier maintenance, the library part is generic and if something needs to be done another way you're able to by simply deriving from the given interfaces or classes itself within your application, the application itself is always specific (even when the differences can be close to none), so i would have to integrate the changes of the library part allover again to the different branches, if it would be included in one single repository, that way all is detached and much easier to maintain.
Common Information
The source itself can be found here (Application), here (library) and here (gradle base for android studio), feel free to send me pull requests
The generic apk is also available at the play store (NOTE: don't flash files from it unless you use a GT-I9300, also note the broken downloads are intended to show the different states).
Changelog
The full list of commits can be viewed here (application) and here (library)
1.0:
Changelist support (listing of updated, added, removed and downgraded packages at startup)
no additional file or work needed, except the present version property at items which should be able to show as downgraded or updated, everything else is done by the app itself
0.9.7.1:
Fixed Index out of bounds crash
Fixed 2 nullpointer crashes
Started to add changelist of content support (changelist of added or removed items from the remoterepository)
0.9.7:
Improved install logic
Improved build.prop property reading
Fixed wrong finished state at service while downloads still processing
0.9.6:
Fixed showing of restore menu item directly after backup;
Fixed caching/loading of download queue onStop/onRestart;
Fixed removing of cached queue onDestroy;
Fixed crash at add file dialog if it is closed before choosing an activity;
Fixed wrong "all finished respond" of service while still processing;
0.9.5:
Completely revised the structure of buildbox (is now splitted into 2 repositories, one for the library [includes the whole logic, main views,...] and one for the implementation of the main activity and for resource overriding [MainActivity, TabAdapter, ...)
Added device filter property (can be applied at every level except at the detail items) (uses the ro.product.model build.prop property for comparsion)
Many fixes and enhancements
0.9.3:
Fixed adding files from storage
Fixed crash at startup without internet connection available
0.9.2:
Apk handling fix
Recovery script fix
0.9.1:
Revised Install procedure for apks (thx to lowveld for the hint)
Fixed root shell command execution (sry)
small additional changes
​
XDA:DevDB Information
BuildBox, a App for the No Device
Contributors
Tectas, http://forum.xda-developers.com/member.php?u=4189659
Version Information
Status: Stable
Current Stable Version: 1.0
Stable Release Date: 2013-10-17
Current Beta Version: 2.0
Beta Release Date: 2013-11-29
Created 2013-11-26
Last Updated 2013-11-29
Reserved
Beta Changelog (To get automatic updates of the beta via play store, join the BuildBox Community and use the opt-in link)
The full list of commits of the test branch can be viewed here (application/2.0-dev branch) and here (library/2.0-dev branch)
2.0:
OnDemand loding of json items (means not the full list must be provided as one file, it can contain urls to other json files which get loaded on demand)
complete overhaul of UI - dropped tabs, g+ dropdown instead, sidebar not present yet, but in the lane already
Hello.!
i m due to make a rom next month, was thinking where to start, guess u solved the problem
anu.cool said:
Hello.!
i m due to make a rom next month, was thinking where to start, guess u solved the problem
Click to expand...
Click to collapse
Happy i could help you decide^^
If you have any thoughts for enhancement, just tell
Beta Added
Like said, 2.0 is BETA, it's not properly working yet (backstack doesn't work completely yet) and not everything is present what should yet (sidebar), the basic features from 1.0 are still functional though.
Beta Changelog
The full list of commits can be viewed here (application) and here (library)
2.0:
OnDemand loding of json items (means not the full list must be provided as one file/webserviceresponse, it can contain urls to other json files which get loaded on demand)
complete overhaul of UI - dropped tabs, g+ dropdown instead, sidebar not present yet, but in the lane already
New beta is ready to download, backstack is fixed.
Tectas said:
New beta is ready to download, backstack is fixed.
Click to expand...
Click to collapse
How do we get on the beta channel for this app?
Sent from my SGH-I337 using Tapatalk
Sc4ryB3ar said:
How do we get on the beta channel for this app?
Sent from my SGH-I337 using Tapatalk
Click to expand...
Click to collapse
Just switch to the downloads tab, there is the beta download as well.
Gesendet von meinem GT-I9300 mit Tapatalk
BuildBox community added with beta testing over play store opt in.
BuildBox Community

[App][Code project][5.0+]Rom Control app for devs

Hello ya'all,
This is gonna be a long op, I dunno where to start...
Sooooo... a while ago a friend (@tdunham) asked if we could share a settings app we made for our rom(s) (future rom(s).... as we are lazy bums). Since we mostly aimlessly wander around xda and help other devs instead of releasing our stuff, we figured... what the hell, we might as well make it into a source code project in a java-unexpirienced-dev format. So here we go!
About the project:
This app has a main function of coordinating content resolver entries between user end (your rom control app) and mods end (when you use content resolver to reitrieve settings storage database entry keys in various modded system apps).
Basically, you create a preference item, such as switch preference f.e, and when the user switches it, an entry is being overwritten in Settings.System. From there, your modded apps, according to your mods, can read the value and do some stuff...
Needless to say that this app requires, among many other things, your ability to mod system apps to use content resolver. If this doesn't mean anything to you, you're in a wrong place.
If you wish to learn more about modding smali using content resolver, you need to first get introduced to 2 amazing threads:
1. Creating and Understanding smali mods by @Goldie - if you are not fluent in that thread, you will not need this app.
2. Galaxy s5 unified mods and guides thread by @tdunham - not all guides there are using content resolver, but lately more and more are. In any case it's a great place to ask questions, learn and contribute.
Nuff said about modding, now to the project
Project characteristics:
The project is a source code project. Meaning we are not providing an application and you will not be using it by decompiling it with apktool. There are so many reasons for that that I don't know where to start. Mainly - it's bad enough samsung has made hackers out of all of us and we need to decompile and backdoor their system apps to mod them. What we can provide in source code - we will. We strongly believe in the freedom of code and we share it unconditionally (almost).
Now what is that "almost? part? Simple... You do NOT need to credit us in any of your work, you do NOT need to thank us, you do NOT need to ask permission to use this project in your rom, you also do NOT need to donate to us (you also can't, we don't have a donate button). YOU DO NEED TO RESPECT THE FREEDOM OF CODE! That means that this code is given to you under the GNU GPL (General Public License). You can review it fully here.
The most relevant part to our discussion is as following:
...For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights...
Click to expand...
Click to collapse
That being said, the only thing that is required of you is that you keep sharing the code. We are not going to run around xda and "police" people using the code and not providing source. We rely on your word, that by agreeing to use the open source, you will keep it public and provide your sources as well for others to use. This VOIDS xda rule number 12, stating that each dev owns their work. Becasue the rule also states that work that is provided by a lisence that negates exclusivity, is therefore not exclusive. Any work based on this code is not to be held exclusive. And if another developer wants to use an app you built based on this code, you have an obligation to provide your sources and to keep those updated to most recent version of the app you release in order to be compliant.
Thread rules and disclaimaers:
The code is 100% original and written by us (myself and @wuby986) for this specific project. All the classes imported from public open source repositories are annotated with original developer signature and our modifications are annotated and dated as well.
To answer most asked question so far - we don't know how it is different from a custom settings app by ficeto. We have never used it in our roms and we have nerver seen it's code (neither have you). Both apps share the same idea of integrating preferences into settings db using content resolver. You are free to use any app you like. We are not saying which app is better or worse. This is seriously not a competition.
This project requires extensive knowledge in android development. As mentioned above, if you don't know how to mod system, this app is of no use to you. We will not be answering questions about smali mods.
This project requires basic knowledge in operating android studio. You need to have it installed and operational in order to work with the code. You need to have android sdk and all the support libraries updated.
This project requires SOME coding expirience or AT LEAST an open mind to getting a crash course. You will not be required to do heavy java lifting to use this app, but it would help if you knew alittle bit.
We cannot teach you how to use android studio, debug problems related to it and so on. We will provide basic instructions as to how to add items to the navigation drawer list, how to add preference fragments with ease, we will explain the idea of out code and different preferences to you. Beyond that - it's on you. We cannot and will not teach you to be a programmer. If you want to know more - the web is wide and google is your friend.
We cannot debug your code problems. This thread is for development discussion related to the project itself. If you need some requests, questions regarding exsisting code, remarks, improvements, you're more than welcome to join a github project and commit your code for everyone's benefit.
Nuff said about rules, moving forward:
Project sources:
Github source for the Rom Control application is here
Github source for the template to add preference fragment for this specific app is here
Initial instructions:
Download and install Android Studio and android sdk for your platform. Make sure all are updated
Go to the preference fragment repository and download the master as zip. Extract the zip contents into /your android adt directory/android-studio/plugins/android/lib/templates/other/
Reopen android studio
File > New > Project from Version Control > Git
The git repository is https://github.com/daxgirl/CustomSettingsForDevs.git
Specify your parent directory and directory to contain the project (will be suggested by studio)
Clone from git
Done you have the project on your pc. Wait for it to sync and build gradle.
The next couple of posts will explain extensively how to operate the app and create customize it to your rom's needs.
XDA:DevDB Information
[App][Code project][5.0+]Rom Control app for devs, App for all devices (see above for details)
Contributors
daxgirl, wuby986
Version Information
Status: Testing
Current Stable Version: 1.0
Created 2015-06-30
Last Updated 2016-04-12
Basic info and app structure
Basic info and app structure:
This application is Navigation Drawer application material design style. It uses app cpmpat in order to use the pager adapter. This can make theming alittle bit tricky, but we provided 2 themes for now which you can modify in styles.
Navigation drawer opens from the left and it contains for now example of navigation items list. For now we have 4 preference fragments and the last items is to set theme. You can add or remove fragments as you wish. The process will be fully explained.
The fragments in the main view container are being replaced based on a position of clicked item in the navigation drawer list. Remember (we will get back to it again), positions in any array begin from 0. That means that for now we have 0,1,2,3,4 items in the arrays that construct the navigation items list. When we add one, we will need to add a title and an icon (both in corresponding positions) and also add our new fragment to a special method which makes the selected items to show specific fragment. We will discuss it at lenght.
For now application contains only preference fragments. If you feel confident and know what you're doing, you can add all kinda fragments and navigation items (even more activities). We concentrate here on preference fragments, because this is the essence.
Each navigation fragment has a java class which extends PreferenceFragment and an xml file inside res/xml folder, where the preferences exist for each fragment. Once launched for the first time, each fragment will create a shared preferences file inside our "home" directory. Our directory is in /data/data/com.wubydax.romcontrol/. There you will find several files and dirs. One of them is called shared_prefs. Inside it each fragment will host it's preference xml file. The name of this file will be identical (by our design) to the name of the xml file for that fragment in /res/xml folder. Once the fragment displayed for the first time, the shared preferences file for it is created and being populated by the default values you set. We will explain later which preferences must have defaultValue set and which preferences MUST NOT.
If you open the java class for any PreferenceFragment, f.e. UIPrefsFragment.java, you will see that the code is very small. That is because we wanted to make things easier for you and we created a class called HandlePreferenceFragment.java, which manages all the work of the fragments.
When you create a new Preference Fragment using a template for android studio we provided, The fragment and it's xml file are created for you automatically. All you will have to do is add it to the item selector in the navigation drawer, of course give it a name and an icon, and you can gop ahead and populate the xml file with preferences. You will not need to touch java anymore if you don't want to.
We have the usual preferences that you know of, like SwitchPreference, CheckboxPreference, ListPreference etc, and we have our own "special" preferences to make your life easier. Those are IntentDialogPreference (to choose an app and write it's intent to the database for you to use in your mods to open apps), FilePreference (to control some booleans by creating and deleting file), we have 2 special kinds of PreferenceScreens: one for running shell scripts and one for creating intent to open apps from the control app. Those preferences will have special kind of keys, which we will demonstrate. You will not need to flash your scripts when flashing your rom. All your scripts will be managed in the assets folder and copied on run time to our home directory and executed from there. You don't need to worry about permissions, all is taken care of. Just place your scripts inside the assets folder before you compile the sources. Sae thing with opening apps as intents, all you need to do is put a main activity full name as PreferenceScreen key. Everything else is taken care of, including displaying icon. The preference will not show at all if the user doen's have an app installed. So no crashes upon clicking on non existing intents. They will just vanish from the list.
The preference files inside the project on github contains BOGUS preferences to use as an example. We will go over all of them (most contained inside first fragment - UIPrefsFragment). They are all active. But they should not trigger any mod, as you should not have those keys in your database. You can see f.e. that preference fragment "Useful apps" has like 5 preferences for app intent. some of them have bogus intent. They will not display when you run your app. They are therer to demonstrate that if the app doesn't exist, you should not worry about FC of Rom Control. It takes care of itself.
The first time the app boots it asks for root permissions. If the device is not rooted or permissions not granted, the app will never run. You all run rooted and modded roms, this app is not for stock. If you wish to disable this function, we will provide that option.
Reboot menu - on the right upper corner of the action bar you will see a reboot icon. Clicking it will show a display of 5 reboot actions: reboot, hotboot, reboot recovery, reboot download, reboot systemui. Youc an access those easily no matter what fragment you're in. Clicking outside of them or clicking back button will make the menu disappear. clicking on one of them will result in immidiate reboot function. Those are root related finctions. We can make them no root dependant once you all use an app in your /system/priv-app. Which, btw, is where we recommend it goes.
How does it work?
For the first time an app is opened (or any time an ap is opened), there is a special method inside HandlePreferenceFragment that is called initAllKeys();. This method goes over all the preferences contained inside the shared preferences for that fragment. One by one it checks their key name, checks if they are of type boolean (true or false), of tipe integer (number) or of type string (words). Then it checks what preference they belong to. It checks if the key for that preference exists in your settings storage database, if it does not - it creates all keys. If the key exists in the database but is different from what the app has - it replaces the one in the app preferences with what you have in your system. That is why it's important for most preferences to set the defaultValue that you wish to be the default, beucase the first time the app launches, it will create all the keys in the system database. once the process is done(you will not see or feel it), your preferences are yours to control. Once a user clicks on Checkbox, if it's selected (isChecked), it writes 1 to the key for that preference inside the Settings.System. and vice versa. Any change in the preferences is being registered immidiately. So your mods can be updated (provided you have observers, of course, or else you might need to reboot apps, just like you always did). Inside the class HandlePreferenceFragment there is a method updateDatabase. it is being called from a method that "wacthes"/"listens" to any change in preference.
That is, basically, all. This is how it works. Everything else is cosmetics made for your convinience and mostly based on your requests. F.e. running shell scripts, FilePreference, App picker preferences was requested by other developers to be included so we had to find a way to build in. Now you can all enjoy. Any further requests are welcome.
Overall structure in studio:
One you have opened the project in studio, you have the following structure tree on your left. Make sure you have chosen the "project" tab (far left edge of the screen) to see it:
Inside the libs folder we have the roottools jar made by the amazing @Stericson and the next folder that is of interest is the src/main. This is where the app as you know it (from apktool) is hosted. You can see inside the res folder all our resources.
If you need to change the icon for the app you need to place it inside mipmap folders. It's called ic_launcher.png. For nice app icons generator visit here . Inside the values-21 folder there is the styles.xml file that you need to edit if you want to change theme colors. Nice site for coherent material palette is here and google documentation is here.
In the main drawables folder you will find those:
As you can see there are two images there that are relevant to you: header_image and header_image_light (for both themes). Thopse are the header images for the navigation drawer. You can replace them with your own. The reference to them is inside /layout/fragment_navigation_drawer.xml as you can see here:
.
Here it's used as an attribute. You can read more about using attrs in android docs. Just replace the images and keep the names.
Inside of the resolution dependant drawable folders you can find the images for the items in the navigation drawer:
Here you can replace, move and add your own. Good resources for icons are: here and here and you can find many more out there.
Inside the assets folder we have a folder named scripts. It's important the name remains "scripts".
It's used in java code to copy the assets on runtime to our home dir. Inside scripts you put your shell scripts that you wish to run using the script running method. scripts have to be called with .sh in the end. When you create a PreferenceScreen that needs to run scripts, you give it a key like this: android:key = "script#nameofourscript". You do not add the .sh in the key. Look at the example inside ui_prefs.xml in PreferenceScreen with key android:key = "script#test". This runs the script that is currently found in assets. which basically writes into a file on your sdcard. Here you can put scripts as complex a you like. The code checkes for the exit code of the script. as long as it is 0, it will print a toast "executed successfully" upon clicking your preference. To try it run the app on your phone and click on a preference screen with summary "Click see what happens". Make sure your scripts are well formed and test them before including. Remember that you're under sudo. Linux shell will execute anything under sudo without asking.
Inside the /res/xml folder are our preference xml files. This will be your main playground. In those files we will be adding the preference items to appear in each of your fragments.
And finally for the java classes:
Here is where all the work is being done in real time. If you don't have expirience, you won't have to go there besides when you need to add the more nav drawer items.
Adding a new fragment and navigation drawer list item:
1. Provided you read the OP instructions and cloned the Rom Control Preference Fragment template repository into /your android adt directory/android-studio/plugins/android/lib/templates/other/, you need to restart android studio and we are ready to go.
2. Right click on the main java package of out application and navigate to New > Fragment > Fragment (6thGear Preference Fragment) like you can see on the picture below:
Once you click on adding the fragment the foloowing window will open:
As you can see the initial names are: for fragment - BlankFragment and for xml blank_prefs. You can change it as you like. BUT! Leave the word Fragment. Once you change the FIRST part of the fragment name, the first part of the prefs file name will be changed automatically. See the img below:
So we have chosen to create a new fragment called PowerMenuFragent and below that we have the preference xml name. the name is automatically generated as you put in your class name for the fragment. The java naming convention states that a class must begin with capital letter and all meaningful words in class name must also begin with capital letter. The xml name generator will split the word Fragment from your class name and make the other words into xml legal name form separated by under score and will add _prefs in the end. So it becomes power_menu_prefs.xml.
Click "finish" and you have a new fragment class and a new xml file for it inside /xml folder. The fragment will look like this:
You don't need to edit it. It's done in template. It instantiates the class called HandlePreferenceFragment and refers to it's main methods. For more infor you can read my annotations in the HPF class.
Your new xml file is now empty and contains an empty preference screen like so:
We will populate it with preferences later.
Now we need to make this new fragment REACHABLE for user. So we need to add an item to the navigation drawer sections. Let's do that:
1. Open /values/strings.xml and find an array of strings. we will add our new item name in a place we want. In this case I will add it after the Framework section (in blue):
Code:
<string-array name="nav_drawer_items">
<item>SystemUI Mods</item>
<item>Phone Mods</item>
<item>Framework and General</item>
[COLOR="Blue"][B]<item>Power Menu</item>[/B][/COLOR]
<item>Useful Apps</item>
<item>Set Theme</item>
</string-array>
2. Now you will need a new icon to appear to the left of the section name in nav drawer. You can add your own icon at this point. It's a good practice to add images for all resolutions. But who are we kidding? You're making a rom for one device. So to remind you, s4, note3, s5 are xxhdpi and note4, s6 are xxxhdpi. I will use existing icon called ic_reboot.png for this section.
3. Now we need to get our hands dirty and go into java alittle. Open MainViewActivity and find the following method. This method is well annotated for your use. So you can refer to it every time you add an item for reference of how-to. Observe the new blue item:
Code:
//Creates a list of NavItem objects to retrieve elements for the Navigation Drawer list of choices
public List<NavItem> getMenu() {
List<com.wubydax.romcontrol.NavItem> items = new ArrayList<>();
/*String array of item names is located in strings.xml under name nav_drawer_items
* If you wish to add more items you need to:
* 1. Add item to nav_drawer_items array
* 2. Add a valid material design icon/image to dir drawable
* 3. Add that image ID to the integer array below (int[] mIcons
* 4. The POSITION of your new item in the string array MUST CORRESPOND to the position of your image in the integer array mIcons
* 5. Create new PreferenceFragment or your own fragment or a method that you would like to invoke when a user clicks on your new item
* 6. Continue down this file to a method onNavigationDrawerItemSelected(int position) - next method
* 7. Add an action based on position. Remember that positions in array are beginning at 0. So if your item is number 6 in array, it will have a position of 5... etc
* 8. You need to add same items to the int array in NavigationDrawerFragment, which has the same method*/
String[] mTitles = getResources().getStringArray(R.array.nav_drawer_items);
int[] mIcons =
{R.drawable.ic_ui_mods,
R.drawable.ic_phone_mods,
R.drawable.ic_general_framework,
[B][COLOR="Blue"]R.drawable.ic_reboot,[/COLOR][/B]
R.drawable.ic_apps,
R.drawable.ic_settings};
for (int i = 0; i < mTitles.length && i < mIcons.length; i++) {
com.wubydax.romcontrol.NavItem current = new com.wubydax.romcontrol.NavItem();
current.setText(mTitles[i]);
current.setDrawable(mIcons[i]);
items.add(current);
}
return items;
}
As you can see I added a line R.drawable.ic_reboot. What is it? This is an equivalent to public id in smali. It is in fact an integer. So it appears inside integer array called mIcons. Our respurces in android are referenced by capital R. then we have the resource type, in this case - drawable, and then the item name (without extension). Note the order of the id in the array, I added my string after the framework string. So I also add the id for the drawable after the id of the framework drawable. This is vital to understand, as the list is being populated on runtime based on items positions. Items in an array are separated by comma.
4. Now open NavigationDrawerFragment class and you will find the same method there. Please add the same id in the same way there. You MUST do so in both classes every time.
5. Now we go back to the MainViewActivity and we find the following method. it will be right after the getMenu() method we just edited. The method is called onNavigationDrawerItemSelected(int position). This method is responsible for performing action based on which navigation drawer item is clicked by a user. Positions are the positions of items in the List of our objects. So we have so far 6 items out arrays (strings and drawable id integers). That means their positions are 0,1,2,3,4,5 respectively. Look at the method as it appears in the original code:
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
/* update the main content by replacing fragments
* See more detailed instructions on the thread or in annotations to the previous method*/
setTitle(getMenu().get(position).getText());
switch (position) {
case 0:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new UIPrefsFragment()).commitAllowingStateLoss();
break;
case 1:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new PhonePrefsFragment()).commitAllowingStateLoss();
break;
case 2:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new FrameworksGeneralFragment()).commitAllowingStateLoss();
break;
case 3:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new AppLinksFragment()).commitAllowingStateLoss();
break;
case 4:
showThemeChooserDialog();
break;
}
}
Here we have switch case based on position of an item. This is the same as saying: if the position of an item is 0, perform this action, else, if the position is 1, perform that action and so on. Only in this case we say: compiler, switch cases based on integer - in case 0: do something, in case 1: do something else. So we need to add an item after the framework section. Framework section has position of 2 (it's item number 3). So now we add our new fragment like so:
Code:
@Override
public void onNavigationDrawerItemSelected(int position) {
/* update the main content by replacing fragments
* See more detailed instructions on the thread or in annotations to the previous method*/
setTitle(getMenu().get(position).getText());
switch (position) {
case 0:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new UIPrefsFragment()).commitAllowingStateLoss();
break;
case 1:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new PhonePrefsFragment()).commitAllowingStateLoss();
break;
case 2:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new FrameworksGeneralFragment()).commitAllowingStateLoss();
break;
[COLOR="blue"][B]case 3:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new PowerMenuFragment()).commitAllowingStateLoss();
break;[/B][/COLOR]
case [COLOR="blue"][B]4[/B][/COLOR]:
getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new AppLinksFragment()).commitAllowingStateLoss();
break;
case [COLOR="blue"][B]5[/B][/COLOR]:
showThemeChooserDialog();
break;
}
}
Note how the new case is now number 3 and the positions of the following cases need to be increased.
Now we can run our app and and there is our new section item:
That's it for this post. Post #3 we will talk about different preference kinds we have and how to use them.
Till then...
To be continued.....​
Handling different kinds of preferences:
Now we roll with populating our preference fragments. Each preference fragment is unique for your needs, depends on your use, your modded apps and categories. All we do, as mentioned above, is provide you with preferences to communicate with your modded system apps using ContentResolver class.
For each preference I will explain:
Does it write preferences into shared preferences? and if it does...
What kind of object it writes to shared preferences of our app?
What kind of value we then write into SettingsSystem database?
What kind of key it uses and why?
SwitchPreference/CheckboxPreference:
Images:
You MUST provide defaultValue for ANY switch preference you create
It writes boolean (true or false) into the shared preferences
We copy it as integer (1 or 0) into the Settings.System database
It mush have a unique key, none of existent in databse. It must be the same key as you use in your mod for that function. F.e. statusbar_clock_visibility. Clock can be either visible or invisible. So switch preference will serve us good here. Also will checkbox preference. In your mod when you retrieve and integer using ContentResolver you specify the default value (if the key is not found). You have to specify the same default value here. If in smaly it was 0x1,. then in the app it must be android:defaultValue = "true". YOU MUST SPECIFY DEFAULT!
In preference xml inside your empty PreferenceScreen claws, you add this:
Code:
<SwitchPreference
android:defaultValue="true"
android:key="clock_visibility"
android:summaryOff="Clock is hidden"
android:summaryOn="Clock is visible"
android:title="Set Clock Visibility" />
Code:
<CheckBoxPreference
android:defaultValue="false"
android:key="brightness_visibility"
android:summaryOff="Brightness slider hidden"
android:summaryOn="Brightness slider is visible"
android:title="Notification Brightness Visibility" />
This is all you need. The key will work automatically. The first time the user runs your app it will look for that key in the database, if it finds it, it will copy the value into our app and the switch will be set accordingly, if it does not find it, it will copy the defaultvalue of your preference to the database.
Of course the proper way of using strings for title and summary is by using string resources. In android studio you can create strings resources after you have typed the string. F.e. click on one of the strings, like for title, and on your keyboard press alt+enter. You will be given an option to extract string resource. That is all up to you. If your app is only in english, you don't really need to do that.
ListPreference:
Usually you would create list preference by specifying <ListPreference..../>. We had added some functionality to native android preferences for List and EditText. So we have our own classes that extend those preferences. So when we create a list preference we use our own class, so the preference looks like this:
Code:
<com.wubydax.romcontrol.prefs.MyListPreference
android:defaultValue="2"
android:entries="@array/clock_position_entries"
android:entryValues="@array/clock_position_values"
android:key="any_clock_position"
android:title="Status Bar Clock Position" />
Once you open < in studio and start typing com..... it will give you the options of preferences existing in our app. Just choose the one you need and it will create the name for it. Don't worry if you mistype, it will not compile.
List preference in android persists string. That means that it writes object of string type into the shared preferences. You need to create 2 string arrays for each list preference. One for Entries - what is displayed in the dialog as single choice items for user. and One is for entryValues (what is being written into the preferences). You can from your mod read them as integers or strings using content resolver. f.e., if your values are 200, 300, 400, android will persist them as strings. But when you restrieve them from database in your systemui smali mod, f.e., you can call either getInt (to get them as integers) or getString to get them as strings. Of course strings array like bread, milk, cookies cannot be retrieved as integer. But a string 200 can be either.
When you retrieve a default value in your smali mod, you retrieve f.e. 200. so YOU NEED TO SET 200 as defaultValue. Or in the above case, it's 2. YOU MUST SPECIFY THE DEFAULT STRING!
You do not specify summary for this preference, we take care of it in code. like so:
EditTextPreference:
Code:
Code:
<com.wubydax.romcontrol.prefs.MyEditTextPreference
android:defaultValue="simpletext"
android:key="carrier_text"
android:title="Set Custom Carrier Text" />
This preference also persists string. It also writes string into the database. You retrieve it only as string. Because you can't control what user types. You don't want your modded systemui to crash because a user inputted "bread" and you are trying to read it as integer.
YOU MUST SPECIFY THE DEFAULT STRING for EditTextPreference.
ColorPickerPreference:
Writes and integer into the sharedpreferences and we retrieve integer into the database.
Color integers are special. I will not go into how and why. I have created a utility helper app for devs for this purpose. The app's main function is to convert hex string to integers or to reverse smali hex string. You can find an apk and explanations how to use it here.
Remember, YOU MUST-MUST-MUST SPECIFY defaultValue for ColorPicker in our app!!! and YOU MUST USE ACTUAL INTEGERS to do so properly. Just trust us on that. It's no biggie. You use our app for hex converter to both create your default smali hex value and to create an integer for this app.
The code for ColorPickerPreference:
Code:
<com.wubydax.romcontrol.prefs.ColorPickerPreference
alphaSlider="true"
android:defaultValue="-16777215"
android:key="clock_color"
android:title="Choose Clock Color" />
As you can see this android:defaultValue="-16777215" is an actual integer for color black. You get it by using our app. You put 000000 into the first text field and click the button. The integer that you get is -16777215. We also have color preview available. It's a very useful tool. Use it and you can never go wrong with neither integers nor smali inverse hex values for your default color.
Now note the special attribute called "alphaSlider" in the code. This is a boolean type. By default it's false. Meaning you can create color picker preference with or withour transparency option.
SeekBarPreference - the SLIDER:
Writes integer of the slideer progress into the database. The moment your finger has stopped tracking the bar, an integer is being registered into the sharedpreference and then being retrieved into the databasse.
Code:
<com.wubydax.romcontrol.prefs.SeekBarPreference
min="0"
unitsRight="Kb/s"
android:defaultValue="10"
android:key="network_traffic_autohide_threshold"
android:max="100"
android:title="Autohide Threshold" />
YOU MUST SET DEFAULT VALUE!!!! IN INTEGER!
You can specify special values such as unitsRight, like "%" or "Kb/s" and so on. You can specify the min and the max value. You probably better not specify the summary. But you can if you want.
IntentDialogPreference - App Chooser:
Code:
<com.wubydax.romcontrol.prefs.IntentDialogPreference
includeSearch="true"
setSeparatorString="\##"
android:key="choosen_app_gear"
android:title="Choose App" />
This is a very special preference kind. It was created by request from @rompnit. They use intents from database to open apps in certain mods. You will have to ask them on @tdunham thread how and when they use it. We created this preference from scratch specifically for them. This is a completely custom kind of android preference. It displays a dialog of all your LAUNCHABLE apps (apps that have default launch intent that can be retrieved by using PackageManager method getLaunchIntentForPackage. In other words - all apps that appear in your launcher will appear on the dialog.
What happens when you click on an app? What is being written into preferences is a special kind of string. The srting might look like this: com.android.settings/com.android.settings.Settings or it might look like this com.android.settings##com.android.settings.Settings... this is what you need to create basic intent. You need package name and activity name. What separates them is up to you. You will need to split them in your smali mod into package name and activity name to create intent. We have created 2 special attributes for this preference:
1. setSeparatorString =this is what will separate the package name from the class name. The default (if you don't specify) is "/". Remember that if you use chars that must be escaped in xml, f.e. like hash(#), you need to escfape them by backslash, like so setSeparatorString = "\##".
2. includeSearch - this is a boolean type of attribute. It is false by default. If you specify true, the search field will appear on the dialog above the apps list, allowing your users to search for an app by name inside the list adapter. We also included a list alphabetical indexer. So it's up to you if it's necessary.
Once the app is chosen, the summary for the preference is set to the app name and the icon on the right side will be the app icon.
Your database will contain now the basic component for the intent. What you do with it in your smali is up to you.
DO NOT SET DEFAULT VALUE FOR THIS PREFERENCE!!!
FilePreference:
This is very special kind of preference requested by @tdunham. What is does it creates and deletes file with a certain name in our home files dir. It is located at /data/data/com.wubydax.romcontrol/files
Code:
<com.wubydax.romcontrol.prefs.FilePreference
android:key=[COLOR="red"]"testfile"[/COLOR]
android:summaryOff="File doesn't exist"
android:summaryOn="File exists"
android:title="Test File Preference" />
The reason this is used by some devs, apparently, is when you need to mod smali file, which originates in a class that does not take context as parameter. Without context you cannot call the ContentResolver, so you cannot retrieve from the database. So what you can do instead is create a boolean condition based on existence or non existence of a certain file. File class does not require context. All it needs is to be instantiated as object and be given a string as path. For exampple:
Code:
[COLOR="Green"]File[/COLOR] [COLOR="Blue"]file[/COLOR] = new [COLOR="green"]File[/COLOR]("[COLOR="Purple"]/data/data/com.wubydax.romcontrol/testfile[/COLOR]");
means that object file of class File is a file located at /data/data/com.wubydax.romcontrol/ and called "testfile". In java class File you have a method (boolean) which is called "exists". So a condition can be made like this:
Code:
if(file.exists){
int i = 1;
} else {
i = 0;
}
So you can create a boolean method that will return 0 or 1 based on existence of the file at certain location.
This is the idea behind this preference.
The key for this preference is THE NAME OF THE FILE.
YOU DO NOT SPECIFY THE DEFAULT!!!
The preference looks like switch preference. But it acts differently. Youc an specify summaryOn and Off as you need. It does not write into database. It just creates and deletes the file.
Script executing PreferenceScreen:
As entioned above you can create PreferenceScreen which will execute shell scripts upon click. Example:
Code:
<PreferenceScreen
android:key=[COLOR="Red"]"script#test"[/COLOR]
android:summary="Click see what happens"
android:title="New Preference Screen" />
Note the key format. It has to begin with script#! The part after the hash (#) is the name of the script you wish to execute, in this case the script is test.sh which you can find in the source you pulled inside assets folder..
Where are the scripts??? You put them inside assets folder (see post #2). You name your scripts f.e. test.sh script (has to end with .sh). But you do not add the .sh extension to the string (we do that in code).
Every time your app launches it checks for scripts in the assets folder. It wants to make sure all the scripts ar being copied to our home dir. Inside files folder there we create a folder called scripts. All your scripts will be automatically copied there from assets, given permission 0755 and ready to be executed.
Wgen a user clicks on a Script Executing PreferenceScreen, the app looks if a script with that name exists in our files dir. If it does, it attemts to execute it. I have explained in post #2. We also check just in case that the script is executable. There is native java method to do that. So if you or your user just add a script to the scripts folder in home directory and forgot to make it 0755, we do that for you in java with this method:
Code:
if (script.exists()) {
[COLOR="Blue"][B]boolean isChmoded = script.canExecute() ? true : false;
if (!isChmoded) {
script.setExecutable(true);
}[/B][/COLOR]
Command command = new Command(0, pathToScript) {
@Override
public void commandCompleted(int id, int exitcode) {
super.commandCompleted(id, exitcode);
if (exitcode != 0) {
Toast.makeText(c, String.valueOf(exitcode), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(c, "Executed Successfully", Toast.LENGTH_SHORT).show();
}
}
};
try {
RootTools.getShell(true).add(command);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
}
Make suer your scripts are of valid shell format, test them separately before you put them in the app. Be careful, all the scripts are being executed under sudo. Means anything you write shall be done. Do not make mistakes in your script. Adding su to your scripts is not necessary. We execute them as root anyway.
So...
Create a shell script and test it on your device
Place it inside the assets folder of your app
Call it f.e. killbill.sh
Create a PreferenceScreen entry and givie it a key android:key = "script#killbill"
Compile the app
Clicking on that preference should execute killbill.sh which will now be foind in /data/data/com.wibydax.romcontrol/files/scripts/killbill.sh and have permissions 0755.
DO NOT SET DEFAULT FOR PreferenceScreen EVER!!!
Intent opening Preference Screen:
Code:
<PreferenceScreen
android:key=[COLOR="Red"]"com.wubydax.gearreboot.RebootActivity"[/COLOR]
android:summary="Opens TWSwipe app to help you choose a different swipe activity"
android:title="Reset TWSwipe Action" />
This is a regular preference screen, so it would seem, but it has a special function. Usually, in order to open an intent with PreferenceScreen, you need to specify a whole lot of intent rules, like action, target class, target package and so on. We have made your life easy. If you want to link to an app from your rom control application, all you need to do is to specify the activity you wish to run as a key to this preference.
You are not allowed to use "." in any other preference key. If you use "." the app will read it as possible intent. If it cannot resolve it, it will make it disappear from the list.
This kind of preference is fully automated. Once the app reads the key, it does all the work for you, it sets the icon for the preference as the app icon, it creates a viable intent.
If the user doesn't have an app that you link to installed, the app will never appear in the preferences. So the user can never click on it. Because otherwise it would give FC to the app.
Nested PreferenceScreen:
If you include regular preference screen, you never need to set a key. Preference screen that envelops the items inside of it will always lead to a nested preference screen that has some included preferences. and so on. We have a loop running through your entire preference tree and detecting all your preference screen and differentiating them by their abilities (being script executing, being intents and so on).
Nested Preference Screen would look like this:
Code:
[COLOR="Red"]<PreferenceScreen
android:summary="New Preference screen"
android:title="New Preference Screen">[/COLOR] [COLOR="Green"]<-- Start of nested preference screen[/COLOR]
<PreferenceCategory android:title="new category" />
<CheckBoxPreference
android:key="text_checkbox"
android:title="Checkbox" />
<SwitchPreference
android:key="test_switch"
android:title="Switch" />
[COLOR="Red"]</PreferenceScreen>[/COLOR] [COLOR="Green"]<-- End of nested preference screen[/COLOR]
Inside of it you can have more preferences and more preference screens.
PreferenceCategory:
Preference category is an enveloping kinda preference. It is different in color and appearence then the rest. It makes sub-portions of preference screen look separate from each other and easier to identify. F.e.:
Code:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
[COLOR="Red"] <PreferenceCategory android:title="Status Bar Mods">[/COLOR] [COLOR="Green"]<-- start of preference category[/COLOR]
<SwitchPreference
android:defaultValue="true"
android:key="clock_visibility"
android:summaryOff="Clock is hidden"
android:summaryOn="Clock is visible"
android:title="Set Clock Visibility" />
<CheckBoxPreference
android:defaultValue="false"
android:key="brightness_visibility"
android:summaryOff="Brightness slider hidden"
android:summaryOn="Brightness slider is visible"
android:title="Notification Brightness Visibility" />
<com.wubydax.romcontrol.prefs.MyListPreference
android:defaultValue="2"
android:entries="@array/clock_position_entries"
android:entryValues="@array/clock_position_values"
android:key="any_clock_position"
android:title="Status Bar Clock Position" />
<com.wubydax.romcontrol.prefs.MyEditTextPreference
android:defaultValue="simpletext"
android:key="carrier_text"
android:title="Set Custom Carrier Text"
/>
<com.wubydax.romcontrol.prefs.ColorPickerPreference
alphaSlider="true"
android:defaultValue="-16777215"
android:key="clock_color"
android:title="Choose Clock Color" />
<PreferenceScreen
android:key="script#test"
android:summary="Click see what happens"
android:title="New Preference Screen" />
<com.wubydax.romcontrol.prefs.SeekBarPreference
min="0"
unitsRight="Kb/s"
android:defaultValue="10"
android:icon="@null"
android:key="network_traffic_autohide_threshold"
android:max="100"
android:title="Autohide Threshold" />
<PreferenceScreen
android:summary="New Preference screen"
android:title="New Preference Screen">
<PreferenceCategory android:title="new category" />
<CheckBoxPreference
android:key="text_checkbox"
android:title="Checkbox" />
<SwitchPreference
android:key="test_switch"
android:title="Switch" />
</PreferenceScreen>
<com.wubydax.romcontrol.prefs.IntentDialogPreference
includeSearch="true"
setSeparatorString="\##"
android:key="choosen_app_gear"
android:title="Choose App" />
<com.wubydax.romcontrol.prefs.FilePreference
android:key="testfile"
android:summaryOff="File doesn't exist"
android:summaryOn="File exists"
android:title="Test File Preference" />
[COLOR="red"]</PreferenceCategory>[/COLOR] [COLOR="Green"]<-- end of PreferenceCategory[/COLOR]
</PreferenceScreen>
This is it for now, more per demand and need. Have fun!​
General tips and tricks
Some tips and tricks
Running app and debugging:
Android studio provides you with built in logcat. Not only that you can debug the app you're working on, you can debug any app you're modding too. Just need to specify the filter for the logcat and the package name. Dig in and you will find some cool features.
You need to have unknown souces enabled and usb debugging enabled to run your compiled app directly on your device.
1. You can install and run this app as user app. It does not need to be system app. For now no features require it. You can of course include it as system app in your rom. We recommend pulling the base.apk from data folder and pushing to /system/priv-app
2. You do not need USB cable to debug and run your app from studio. There is anifty app I am using. You can download it here https://play.google.com/store/apps/details?id=com.ttxapps.wifiadb&hl=en. All you need to do is open the command line on your pc and type adb connect <ip number of your phone in the network>:5555. The app will provide you with an IP number.
Now studio will recognize your device as USB debugging device even though it's not connected with usb cable. I just hate cables.......
Including key specific functions:
For now all our work is done automatically for us. You click a preference and the work is done. But what if you have a key that you want to do alittle more with than just write into database? I will give you an example.
We have a SwitchPreference in our app that enables/disables call recording. That mod requires restart of InCallUI.apk. Now you can of course restart it by creating a Script Running PreferenceScreen item called Reboot InCallUI and it will be fine. That's what you have been doing so far. But let me show you what you can do now that you own your source code.
We have two ways to kill that app. Silently (without user knowing - very cool) or informing the user. Let me show you how it would be done.
Let's say you create a preference for call recording:
Code:
<[COLOR="red"]SwitchPreference[/COLOR]
android:defaultValue="true"
android:key="[COLOR="Red"]toggle_call_recording[/COLOR]"
android:summaryOff="Call recording is disabled"
android:summaryOn="Call recording is enabled"
android:title="Enable/Disable Call Recording" />
The two things we need to know is the key and the class instance of preference - which is SwitchPreference.
Let us go to the java class HandlePreferenceFragments and find a method called public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){}}. In android studio you can search through class by pressing ctrl+f.
In that method we have switch by the preference class name (INSTANCE). So we have this case:
Code:
case "SwitchPreference":
SwitchPreference s = (SwitchPreference) pf.findPreference(key);
s.setChecked(sharedPreferences.getBoolean(key, true));
break;
What this means is: if the preference is of kind SwitchPreference, when the preference is changes, do something..... So.... let us do something with our SPECIFIC switch preference for our SPPECIFIC key!!!
Let us try this:
The silent way:
Code:
case "SwitchPreference":
SwitchPreference s = (SwitchPreference) pf.findPreference(key);
s.setChecked(sharedPreferences.getBoolean(key, true));
[COLOR="Blue"][B]if (key.equals("toggle_call_recording")) {
Command c = new Command(0, "pkill com.android.incallui");
try {
RootTools.getShell(true).add(c);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
}[/B][/COLOR]
break;
This will kill the InCallUI every time the user switches that switch. So what happened here? The user switched the switch, the boolean got written to the database (in a different method), then the app relevant to this key was restarted. Next time a user makes a call - the call recording will be updated!!!
Now let us do it in a no silent way:
Let us inform the user. We have a little method in that class called public void appRebootRequired(final String pckgName) { ...}. Let us try to use it...
So let us go back to our onSharedPreferencesChanged method and instaed of the condition we used silently, we do something like this:
Code:
case "SwitchPreference":
SwitchPreference s = (SwitchPreference) pf.findPreference(key);
s.setChecked(sharedPreferences.getBoolean(key, true));
[COLOR="blue"][B]if (key.equals("toggle_call_recording")) {
appRebootRequired("com.android.incallui");
}[/B][/COLOR]
break;
The user clicks on the preference and see what happens:
Now for InCallUI it might be better to restart the app silently. Since the change is not visible to user anyway. But if you need to restart systemui, then it might be better to inform the user. So all you need to do is instead of passing a string "com.android.incallui" pass a string "com.android systemui". The method will do everything automatically. See how the dialog changes:
Adding more than one special key
If you need to add more than one special key (see popst #3 for instructions and explanations), you have 2 options:
1. We can go on with the if/else conditions, like so:
Code:
case "SwitchPreference":
SwitchPreference s = (SwitchPreference) pf.findPreference(key);
s.setChecked(sharedPreferences.getBoolean(key, true));
[COLOR="blue"][B] if (key.equals("toggle_call_recording")) {
appRebootRequired("com.android.incallui");
} else if (key.equals("some_other_key")) {
//do something you want
} else if (key.equals("again_some_key")) {
//do something different
}[/B][/COLOR]
break;
2. Or we make a switch for that based on key. Like so:
Code:
case "SwitchPreference":
SwitchPreference s = (SwitchPreference) pf.findPreference(key);
s.setChecked(sharedPreferences.getBoolean(key, true));
[COLOR="Blue"][B]switch (key){
case("toggle_call_recording"):
appRebootRequired("com.android.incallui");
break;
case("toggle_clock_visibility"):
appRebootRequired("com.android.systemui");
break;
case("some_other_key"):
//do something
break;
case("some_other_different_key"):
//do something different
break;
}[/B][/COLOR]
break;
Please note:
You can add the specific conditions to any preferences
You need to add them to the same preference instance as the preference that the key belongs to. Right now I showed how to do it for switch preference. You can do the same for any preference. If the key belongs to checkbox preference, you need to put the conditions inside the case of the "CheckBoxPreference" and so on
You need to make sure your condition comes AFTER our built in lines. Like in this case I added it after the initiation of the object and setChecked
You need to finish your conditions BEFORE the main break; of the case.
More to come at later time and per demand...
Huge THANK YOU @daxgirl & @Wuby986 for this!! Folks will love this app!!
Awesome!! Glad to see you have finally released it. I'm sure it'll be fantastic!!
HIZZAH!!! Kudos to wuby and daxgirl!!!
And just when I thought I could take a break from Android.....
The Sickness said:
And just when I thought I could take a break from Android.....
Click to expand...
Click to collapse
You??? Duh.......
Sent from my awesome g920f powered by 6thGear
Thebear j koss said:
View attachment 3384150
HIZZAH!!! Kudos to wuby and daxgirl!!!
Click to expand...
Click to collapse
Mostly to daxgirl
She will say no, but is true
The Sickness said:
And just when I thought I could take a break from Android.....
Click to expand...
Click to collapse
Eheehhehe there is always a good reason to start again
Delivered as promised, great work you 2, thanks a million bunch to you both & to your great testers.
PS : @daxgirl @Wuby986 any chance this app will have the phone make us coffee in the morning ! ( kidding, Sorry )
@daxgirl and @Wuby986 you guys really rock? thanks, thanks and thanks! ?
claude96 said:
Delivered as promised, great work you 2, thanks a million bunch to you both & to your great testers.
PS : @daxgirl @Wuby986 any chance this app will have the phone make us coffee in the morning ! ( kidding, Sorry )
Click to expand...
Click to collapse
Over the past couple weeks @tdunham and @ rompnit definitely tried to make us do that. .. the answer is... of you can make your coffee machine get context and use content resolver, we will deliver the toggle to trigger your morning pleasure
Sent from my awesome g920f powered by 6thGear
daxgirl said:
Over the past couple weeks @tdunham and @ rompnit definitely tried to make us do that. .. the answer is... of you can make your coffee machine get context and use content resolver, we will deliver the toggle to trigger your morning pleasure
Sent from my awesome g920f powered by 6thGear
Click to expand...
Click to collapse
@daxgirl I'm sure if anyone can !, you can, but unfortunately my coffee machine doesn't speak android at all:crying:, anyway thanks a million bunch for all your great work & help & all ( best of luck with the new upcoming rom btw:good: )
claude96 said:
@daxgirl I'm sure if anyone can !, you can, but unfortunately my coffee machine doesn't speak android at all:crying:, anyway thanks a million bunch for all your great work & help & all ( best of luck with the new upcoming rom btw:good: )
Click to expand...
Click to collapse
Thanks! We really appreciate!
As for the rom. .. it will be awhile I guess...
In a mean while I will get back to writing instructions.
Some screenies added to the op...
Sent from my awesome g920f powered by 6thGear
daxgirl said:
Thanks! We really appreciate!
As for the rom. .. it will be awhile I guess...
In a mean while I will get back to writing instructions.
Some screenies added to the op...
Sent from my awesome g920f powered by 6thGear
Click to expand...
Click to collapse
You're most welcome, and thank you of course ( pics ( app ) looks great btw )
PS : about your rom, a word to the wise ( if I may ! ), just make it bug free as much as possible ( witch is no problem for you I'm sure ), don't throw everything in it at 1st ( users will always want more and new stuff of course, normal ! ), again thanks a million and best of luck, keep up the great work.
Amazing! Now I need to fold up my sleeves and start learning something.
Sent from my SM-N9005 using Tapatalk
claude96 said:
You're most welcome, and thank you of course ( pics ( app ) looks great btw )
PS : about your rom, a word to the wise ( if I may ! ), just make it bug free as much as possible ( witch is no problem for you I'm sure ), don't throw everything in it at 1st ( users will always want more and new stuff of course, normal ! ), again thanks a million and best of luck, keep up the great work.
Click to expand...
Click to collapse
This is a wonderful idea and this is exactly our intention always. We are not for being the best or the fastest or the most unique. We are all that in our hearts It's just we are too jumpy from thing to thing... and we never manage to finish a rom between all our ideas... I am starting to think we might not have been meant to
kmokhtar79 said:
Amazing! Now I need to fold up my sleeves and start learning something.
Sent from my SM-N9005 using Tapatalk
Click to expand...
Click to collapse
My dear friend, if anyone can, YOU CAN!!! I have every faith in you!!!
Second post with instructions now contains an explanation of basic idea and how the app works... The rest after I wake up. It's almost 5am here and I am semi conscious... See ya guys tomorrow!
great, good job as always, i was thinking about one thing: when we add a new mod we learned to put our "key" in settings system database, so my idea is:there is a way to make a general observer that read all the "key" in system database so as to update our choices in real time?

[SOURCE CODE][DEV TOOL][SDK 21+]6thGear RomControl v2.+ for Devs

6htGear Rom control V2.1
By @Wuby986 & Daxgirl
Hello everyone!
So here we go again... V2.0
Big thanks:
We would like to begin from crediting people, who gave us ideas, inspiration and, most importantly, their free time, in order to make v2.0 a reality.
To our dearest friends and talented developers, @tdunham and @DaOldMan:
Guys, you OWN this. You made this happen. You pushed us and we pushed you, and together, you, us and rom control, have grown to be what we are today.
No thanks can ever be enough for long nights of applying patches, merging sources, connecting through teamviewer and working out kinks together. @Wuby986 and I are forever in your debt.
Why different thread?
1. The entire application is different. It barely qualifies as an update anymore.
2. All the preferences are different. The way they work is different. It requires new way of doing things. Radically new.
3. new support library and new basic structure.
4. To sum it up... it's too different to maintain same thread for both versions
Project characteristics:
1. Rom control is an open source project, designed to provide rom builders with a core code for compiling android application for controlling core functions of their roms and mods through Content Provider of Settings.System sqlite table
2. Rom control is designed with consideration of the fact that most rom builders do not have sufficient skills in original android development to build application with this functionality on their own
3. The emphasis is given in this version (even more than previous one) to outsource most conditions and attributes to xml, and so to minimize the need of the user (rom builder) to be subjected to java programming
4. In addition to familiar utilization of ContentResolver to pass data between RomControl and system, the project offers additional properties, such as file based preference, URI selection preference, Direct intent to shortcut app preference, preference listing image thumbnails for previews, script running preference, automated template for "About Us" section, automated dialog for changelog, backup and restore finctionality and more.
5. The project is designed to be compiled in Android Studio using the latest sdk tools and gradle tools.
6. The project essentially is designed to be a system application with privileged access, and therefore needs to be installed in /system/priv-app to be granted some of its permissions
7. The project requires root access for some of its functionality. Mainly running shell scripts with su and killing some app processes.
License and sharing policy:
1. This project is distributed under GNU General Public License as open source code. The copy of said license can be obtained and reviewed here
2. As such, this project is protected from claiming exclusivity by anyone.
3. Any developer wishing to use this code, with accordance to the license, must provide full source code for each updated version. That means, for any new version of the rom including updated RomControl application, a link to full source code of the latest version must be provided.
4. By modifying and using this code, you automatically accept the License conditions and must be compliant with GPL, as stated below:
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
Click to expand...
Click to collapse
5. You're under no obligation to thank us, credit us or tag us in your official postings while distributing your copy.
6. You ARE, however, prohibited from removing our copyright information from our source code.
7. You are obligated to keep the code open under GPL. Failure to provide sources for updated copies of your work will result in complaint first to XDA officials for license infringement and further to GPL legal department.
8. Using the source code on any other forum outside of xda is of course allowed with accordance to the license and sharing policy, provided the sources are kept open and obtainable by anyone.
9. Using apktool to compile a copy of this code after making changes in the decompiled form of someone else's application is strictly prohibited, as the developer will not be able to provide full open source of their version. Any illegal use of any copy of this project can be and should be legally stopped by the owner of the code copy.
10. This voids rule number 12 of xda promising a developer exclusivity over their product. This product is yours, but the code belongs to the public. You are NOT TO HOLD COPY OF ROM CONTROL EXCLUSIVE.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Click to expand...
Click to collapse
Open source libraries included in this project:
1. RootTools by Stericson
2. Sergey Margaritov's ColorPickerPreference modified to adopt to our needs
3. CircleImageView by hdodenhof
Project requirements:
1. Installed and updated android sdk, including but not limited to:
Android SDK Build-Tools 24
Android SDK Platform-Tools 24
Android support repository 33
Google repository, rev 29
Latest android support library
2. Android studio version AT LEAST the latest stable version (currently 2.1.2), you can use the canary channel as well, currently on 2.2.0 preview 5.
3. Updated gradle tools
4. Working knowledge of importing project into Android Studio and troubleshooting gradle sync. If you don't know how to, Google it.
5. EXTENSIVE knowledge in android modding:
This project is for rom developers and modders. It helps coordinate between your users and your mods. If you don't build roms or don't have mods, this project means nothing to you.​
What support you can expect to get:
1. Code explanation regarding major functionality
2. Adding new preferences and navigation items
What support you CANNOT expect:
1. Setting up android studio
2. Debugging gradle issues and compiling
3. Changing colors, strings, adding themes, design, changing setup... - Android documentation is vast and Stackoverflow is even vaster.
4. Smali modding
5. Private messaging support - DO NOT EVEN TRY
6. Asking for compiled apk file.
This is NOT an application thread. This is NOT an application. This is a SOURCE CODE for MAKING application.
The answer to a question "Can someone give me a compiled version" is "And what are you going to do with it?"​
Project main Git repository:
Here
Thread list of contents:
Starting the project
Adding navigation drawer items
Running android app: where, how, builds, gradle tasks and you-name-it
Preferences - Part 1: Introduction
Preferences - Part 2: Types of preferences
Themes, About Us activity and Changelog dialog
Backup and Restore
XDA:DevDB Information
6thGear RomControl v2.0, Tool/Utility for all devices (see above for details)
Contributors
daxgirl, wuby986, tdunham, DaOldMan
Version Information
Status: Testing
Current Stable Version: 2.1
Stable Release Date: 2016-08-26
Created 2016-07-06
Last Updated 2016-08-26
Latest Update details:
Post number 195
Step 1 - Importing the project:
1. Perform full installation of the latest stable version of Android Studio in your environment. You can find info about stable and canary releases here
2. You can have more than one version of android studio installed on single platform. For more information please read further on the same page in section Using Multiple Android Studio Versions. I personally do recommend the latest canary build, which is currently AndroidStudio 2.2.0 preview 5. But you can always go with the stable release. Or beta channel.
3. Make sure your sdk is updated, including sdk for platform 24 (nougat). The compile sdk for this project is 24.
4. Make sure your support repositories are configured and updated.
5. Click on our github repository link on the OP first post and make sure you're connected with your github account. If you don't have one - create it! Why? because you will need to share your sources for this project. And because you all use as mantra that you can mod android apps because it's open source. So BE OPEN SOURCE. Have your name on github.
6. Once you're logged in into github, fork our repository. In the right upper corner of our main git repository you have those buttons:
Click "fork" to make a copy of this repository in your own repositories. Now you have your own repository.
7. On YOUR repository find this green button on the top right above the code, which says "Clone and Download". DO NOT DOWNLOAD ZIP. Instead, click the little "clipboard" icon to copy the .git uri and return to studio.
8. In studio: File > New >Project from Version Control > Git
9. Paste the git uri and choose destination. Click ok. Android studio will import the project from git and open it for you.
10. At this point if you're asked to update gradle build tools or anything else, do it. Wait for gradle to sync with project files. If you get errors, resolve them as referenced. If you cannot, google is your friend.
We WILL provide some support for initial importing of the project and setting it up for a very limited period of time. Gradle can be a tricky business. Please be sure to provide us with specific error from gradle log and a line in the gradle script on which the error is made.
11. We WILL know if your errors are because you didn't update sdk and build tools. And we will kick your butts for posting without following instructions. Remember, our time is valuable and given to you for free. Our instructions are clear and we made a huge effort to write them. If you can't be bothered with following them, beware.
12. Once the gradle is done syncing without errors, just in case, click Build > Rebuild Project. Once that is done without errors and it says BUILD SUCCESSFUL, you can start building your project following the instructions on the next post.
Adding items to the Navigation Drawer:
1. Switch to project view.
It will be easier for you to navigate through project files. For that:
On the left panel on top, below the android studio menu, find this:
This is what your project will look right after you import it. This is module view. By default it is categorized and to work with it you need some understanding of this view.
Click the 2 arrow icon which is circled in blue and select "project"
Your structure will now change.
Navigate into the project by the following path: Project name > app > src > main
Now you will see directories, like: java, res, assets... and so on.
This is your working directory. You will be making your code changes here.​
2. Find a file called nav_drawer_arrays.xml. It is located in res/values folder. Double click on it to open.
You will see the following 3 arrays inside. The first one is a reference array (simple typed array) and the other 2 are strings arrays.
Those are WORKING ARRAYS. When you run the app as it is now, you will see all the items created in the navigation drawer based on this info.
Please read the comments we wrote in the xml file for you:​
Code:
<resources>
[COLOR="Green"][B][I]<!--The following array is for icons you want to use for your items
You can create new icons bu right clicking the drawable folder and choosing
New vector drawable
You have a great selection of items in xml vector format.
Those are supported starting lollipop.
YOU SHOULD NOT USE PNG. not even material one. Vectors will work best with any device density.
Once you have created the vector, reference it as regular drawable in the array below.
MAKE SURE THE ITEMS IN ALL 3 ARRAYS CORRESPOND IN ORDER AND ALL 3 ARRAYS ARE SAME LENGTH-->[/I][/B][/COLOR]
<array name="nav_menu_prefs_drawables">
<item>@drawable/ic_system_ui</item>
<item>@drawable/ic_phone</item>
<item>@drawable/ic_framework</item>
<item>@drawable/ic_notification_panel</item>
</array>
[COLOR="green"][B][I]<!--This array is for your items titles.
Use @string reference, so later on your app can be translated with ease
KEEP THE ORDER BETWEEN ALL YOUR ARRAYS-->[/I][/B][/COLOR]
<string-array name="nav_menu_prefs_titles">
<item>@string/systemui_prefs</item>
<item>@string/phone_prefs</item>
<item>@string/framework_prefs</item>
<item>@string/notification_panel_prefs</item>
</string-array>
[COLOR="green"][B][I] <!--This array is the most valuable one
Here you put the file names of the preference files you create in your xml directory
THEY MUST BE PRECISE AND CASE SENSITIVE!!! DO NOT ADD .xml SUFFIX-->[/I][/B][/COLOR]
<string-array name="nav_menu_xml_file_names" translatable="false">
<item>ui_prefs</item>
<item>phone_prefs</item>
<item>framework_prefs</item>
<item>notification_panel_prefs</item>
</string-array>
</resources>
3. Let's say you have 10 preference files in directory called xml. That means you will want to have 10 items referring to your preference files in the navigation drawer. That means you will need to have 10 items in EACH array. Create 10 empty preference files. DO NOT COPY THE ONES FROM RC v1.0. Just right click the xml folder, choose "New" and choose "New XML resource file". Give it a name and click ok. Leave them empty for now. create all the icons you need for them in the navigation drawer.
4. Populate the arrays with titles, icons and xml names. You're done. You now have a working items in the navigation drawer. You do not need any changes in java files. the items are being generated on run time and their onClicks redirected accordingly. If you run the app right now you should have 10 empty preference files.
We strongly encourage you to keep the ui_prefs.xml file and references to it in your project while you're working on it. It contains most valuable information about the kinds of preferences we have included and their various usages. You can remove it from arrays before making the release version. You can have it as last item in your arrays and use it as test dummy to see how things should work properly
Run!
Installing and running your builds in Android Studio:
First of all - data or system app?
The simple answer is SYSTEM. And not just system - we need some high level permissions, so definitely /system/priv-app. Why?
So for that we dig deeper into android permission system.
1. Writing settings into settings storage database:
This permission was revoked from data apps on Marshmallow. Meaning, THEORETICALLY, that only system apps can write into Settings.System. So how come we can write when the app is installed as data app? Oh, this is where THEORETICALLY part comes in. Permission to write system settings is declaired in framework in such a way, that it allows data apps to write there if they target sdk lower than 23 in their build. That permission level is called "pre23". That is why in our gradle we have a somewhat peculiar sdk division for building. Let's look at the image:
As you can see, target sdk is set to 22. This is not by mistake. This is by design so if you want to test the basic functionality of the app by installing debug version in data, it will not crash every time you flip a switch.
This is the definition of pre23, we target sdk 22 so the pre MM permissions can be achieved by running the app in data.
Although all of you will be including this app in your roms in system priv-app, you will be working with it quite alot as you build it. We want you to be able to run it from data if you wish so. if we target sdk 23 and up it will never run from data, unless installed also in system.
You are free to change this to 23 or 24. But NEVER run it while installed only in data then. It will crash like a drunken monkey.
Also, changing it to 23 or 24 for TARGET sdk is meaningless. It's not better because it's a higher number. For target sdk it makes no difference.​
2. Running reboot
We run reboot functions in a proper android shutdown sequence. Any of you that are familiar enough with linux kernel based platforms KNOW the system should not be shut down by killing it's process.
Therefore all reboot functionality in our app is native android reboot. For THAT we absolutely need the app to have an initial copy in priv-app. If the app is only installed in data, clicking on any reboot option, either from reboot menu or from reboot dialogs, will result in FC in your face. the following permissions cannot be obtained by data apps NEVER EVER.
Code:
<uses-permission android:name="android.permission.REBOOT"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.DEVICE_POWER"
tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.RECOVERY"/>
3. But we have root permissions? Isn't it enough?
So here is the thing you should remember:
Android doesn't give a damn about root permissions. When we run command under su we talk to the linux kernel through shell. We do not run it on android level. Android is NOT linux. There is NO android permission which is compiant with su.​When we are talking about android application permissions, we are talking about PackageManager, which is android framework system service, that grants the permissions to perform certain action. Package manager does not know su. It is not part of linux platform. It is android. Android is not designed to have root access. Not on any level. it does not recognize unix commands by default.
So when we execute your scripts, android doesn't do it. Our application code doesn't do it. We just pass it to the kernel as runtime command. Remember that, when you come complaining that your scripts don't run. We can't help it. If the kernel refuses to execute them, something is WRONG in the script syntax or structure.​
4. So data or system? The answer is - when you build and test run your app - BOTH
Can you run apps from android studio while one of the copies is installed in system? Absolutely. As any system app, app is allowed to have an update.
The most important thing is for that update to have same signature and same package as the app in system. Once the app is installed in priv-app it has privileged permissions. You can after that, as oyu build, install updates in data, so you don't have to push every single test build into system and reboot, and all privileged permissions will work.​​
Gradle, baby!
Gradle is a build tool. You can read on history of gradle online. It was not developed with any relation with android. Google decided to adopt gradle as their primary build tool for their primary development environment for android and hence, android gradle plugin was born.
Build tool is a way to "put things together in orderly fashion". In essence, android application is a bunch of files in folders. Making it into a running product is a matter of some complexity. Connecting java to resources, signing, packaging, updating manifest, setting primary configs and build related configs, compiling java, compiling dependencies, including multiple modules, being able to have several builds and flavors in one project - this is what gradle does for us.
If you wish to learn more about gradle for android, please watch this amazing video https://www.youtube.com/watch?v=jJ9j7MvGPkU.
Gradle, in a manner of speaking, is a bunch of tasks. Tasks are executed in specific order. Files are being copied, deleted, compiled and packaged as result of single button click.
Android gradle plugin comes with specific predifined tasks. We can also write our own tasks, which we usually do, for our own usage. We will talk about OUR specific tasks later on in the advanced section.
For now we will talk about basic android gradle tasks, such as assembleRelease, assembleDebug, installRelease, installDebug and so on.
1. Clicking RUN button
If you have a look on the top panel of android studio you have this green "play" button next to a selection box which, usually, says "app". Like this:
This is what will appear on the run menu when you first open the project and it's done syncing with gradle. If the "app" selection box has a red "X" on it, means gradle is syncing now or has failed to sync and you need to find out WHY and fix it. Once there is no red "x" current configuration is ready to run.
When you click the green run button, it will run whatever task is in the selection box. When it says "app" in the selection box and you click run, it will do the following:
1. Compile debug build
2. Install it on your connected device
3. Run it​
So what is "app"? App is the main of the module we want to run. It is the only module in our project. So by running "app", we run the RomControl application on a device in DEBUG mode.
Why is it good to run in debug mode? For 2 reasons:
1. Run "app" configuration supports instant run. You can read more on instant run here. This will push the code changes into your running app on device and apply immediately. It's very handy if you add a preference or 2 and want to test how it looks or works. If instant run is impossible for your current build tools, android studio will tell you and it will tell you why. It usually means that you need to upgrade android gradle plugin. This can be done with ease.
2. Running app module in debug mode will give you full stack trace if there is an error. It will be easier for you to copy the log here for us to have a look at and debug. Or debug yourselves.​
The downside of running debug mode?
1. It's somewhat slow. Meaning the app on the device is a little slow in debug mode (although now it's not as slow as it used to be)
2. Debug mode by definition runs from data. So none of the reboot options will work. So if you want to test actual changes that require reboot from our app, you need to have a system priv-app version installed. You can have a debug version installed in priv-app and then you can use instant run, like we spoke before.​
2. So how do we make a release version?
1. Generating signing key
For that we need a signing key. We already made a full prepared platform for you to run release build in our app gradle build file. All you need to do is create a signature and make some little edits. So, let's roll.
To create a signature please follow these instructions
Please remember or write down the following:
1. Path where you create the signature
2. Key password
3. Store password
4. Key alias​You do not need to generate the release build just yet. Just finish creating your own keystore and remember where you put it.
Now go to the parent folder where your rom control project sits. For example if you put it in AndroidStudioProjects folder, in the same folder create a folder called "keys" (no caps, just "keys"). Copy your keystore there. Or originally create it there.
Now go back to android studio. to the left project panel (provided it is in project view, like we asked you to make it) and scroll down... You will see at the very bottom some singleton files, like gradlew, gradlew.bat, gradle.properties and so on. One of the files there is called key.properties. Double click on it to open.
Inside you will see 4 strings. Like this:
Out in your actual key information. The one you used to create your key. you need to make changes to all 4 fields.
for example:
As you can see we used relative path to the keystore. Which is why it's supposed to be in the parent folder of your folder containing your project in direcroty called "keys".​
2. Telling gradle to use our signing key for release builds
On the left project panel look inside the "app" module folder. On the bottom of it, after the AndroidManifest.xml file, you will see a builg.gradle file. Double click to open it.
This is a gradle file for building our app module. You will see there are alot of configurations related to android build there. It will look something like this:
You need to un-comment the sections pointed to with red arrows. To comment or un-comment the section in android studio, select the section and click "ctrl + /"
Now you should be ready to build the release version. Let's test that:
1. On the right upper corner of the studio window you will see little vertical "gradle" tab. Like this
Click on it. A side window till open with gradle tasks. Like this:
2. Open app > tasks > build
3. Find a task called assembleRelease and double click on it.
4. Wait for it to finish. You will see tons of things running in the gradle console window on the bottom. Provided you didn't mess up any of the previous steps, it will work fine.
5. Once it's done, check that you did now have errors and that build was successfull.
6. If all is good, open in file manager your project folder > app > build > outputs > apk. There you should see your freshly compiled release version. Release version is called simply RomControl.apk. it is already zipaligned and signed. You can go ahead and use it in your rom, push it into priv-app and test. So on.
3. So every time I need to run assembleRelease and push the apk into priv-app and reboot? NO!!!
1. Once you run your first assembleRelease, take that apk and push it into system priv-app. Reboot your device.
2. Now look again into the app > tasks in the gradle window on the right. You also have there "install" tasks. Open it and find "installRelease". Connect your device with app installed already in priv-app and double click on installRelease. This will install the release as UPDATE in the DATA apps. This is so you don't need to push the app to device as you're building and testing. You can make code changes, install release as data and run it FULLY. Becasue you have the original sitting in the system, it will have all the premissions for the reboots. So you can build and test from data.
3. Please remember that as you build and test only the data version of your app is updated. So once you are done testing and the build is final, run assembleRelease and take the final apk from the outpute/apk folder to include in your rom.​
4. Do I need to go to the gradle menu on the right all the time to run installRelease? NO!!!
After you run a task from the gradle menu have a look at the run button on the top panel. Surprise! It doesn't have "app" selected anymore. it has the latest task you ran!!! Look:
Now if you click the "run" button it will run the selected task. If you want to select another task from the tasks you used in the past, Just select from the selection box menu and click run.​
So which build to run and when?
1. If you're building and testing continuously, we recommend keeping the app as debug in data only and NOT TO USE the reboot options.
For adding preferences and building your ui you don't need to use reboot options. Just click LATER on reboot dialogs if you include reboot options.
So you can use instant run, switch to "app" configuration and keep running in debug mode from data as you build.​2. When you go further into preference testing, we recommend uninstaling the debug version. creating signed release version and push into priv-app. From this point on run installRelease task to instal release update in data as you build and correct and test scripts and reboot options.
3. When ready to go final release with your rom, use task assembleRelease to build your final version and include it in your rom zip
4. Commit latest changes to your github repository​
Uploading sources to git
1. Provided you followed our instructions and forked the project source code and then cloned it to studio, it is now connected to your forked git project.
2. Any new file you add will ask if you want to add it to git. And will turn it's color to green if added. Any file that is not added will have brown color.
3. To add brown colored file to github, right click it, choose git > add
4. You should have the following available on the top panel:
The green arrow is for commiting and pushing changes to github. Once you push it the following window will open:
5. Check what files you would like to commit. For example, never commit key.properties file which contains your key password.
6. Write description of your commit and choose from the blue button selector box commit and push.
7. Make a habit of committing your work daily or at least on a new feature basis. It easier to follow for you and also serves as backup.​
We would be happy to talk more about gradle and various tasks, but this post had a specific purpose. To teach you how to manipulate build types and use it to you advantage. Please ask us specific questions about gradle tasks related to your build.
Preferences - Part 1: Introduction
1. Major change in implementation:
1. For this release we made a major change in how preferences are handled. They are not handled anymore. They handle themselves.
2. For that to happen we needed to subclass ALL native android preferences except PreferenceScreen and PreferenceCategory.
3. What does it mean to subclass? That means we created java classses which extend (resemble) native android preferences and we wrote our own implementation of how they should behave, how they should load their values and write their values.
4. That being said - there is no more standard android preferences in this project. No more SwitchPreference, no more CheckboxPreference, no ListPreference... None of those.
5. Two reasons for that:
1. We didn't want you to get lost in special conditions anymore. We wanted you to be able to set if the preference should restart systemui from xml file when you declare preference. For that we needed to add custom xml attributes. For that we needed a preference class to be able to acknowledge that. So we needed a custom preference class.
2. We wanted the preference to manage itself in by reading and writing from and to database. Instead of fragment running endless iterations and conditions. When our new preferences are born (attached to the screen), they get their value from the database directly. No one needs to set values to them. When they are changed, they know to write into database directly. From their own class. Not containing fragment doing that for them.​
2. Types of preferences
1. Two state preferences:
MySwitchPreference
MyCheckboxPreference
FilePreference​
2. Dialog preferences:
MyListPreference
MyEditTextPreference
IntentDialogPreference
ThumbnailListPreference
ColorPickerPreference​
3. Native preferences(PreferenceGroup subclasses):
PreferenceScreen
PreferenceCategory​
4. Slider Preference:
MySeekBarPreference​
5. Special preferences:
OpenAppPreference
UriSelectionPreference
RunScriptPreference
ImageHeaderPreference​
3. Setting defaults:
It is ABSOLUTELY VITALLY IMPORTANT that you set android:defaultValue to all the preferences that change and read values. That means:
MySwitchPreference
MyCheckboxPreference
FilePreference
MyListPreference
MyEditTextPreference
ThumbnailListPreference
ColorPickerPreference
MySeekBarPreference​
4. What happens if we use regular android preferences? Like SwitchPreference or ListPreference?
Nothing! Absolutely nothing will happen nor to this project, nor to your database and, MOST IMPORTANTLY, nor to your mods.
It will act like normal preference. It will not write to database. Your mods will not be affected and WILL NOT WORK.​
5. Custom attributes for value changing preferences and RunScriptPreference
1. app: packageNameToKill
This attribute is of type string and you will need to provide which app you want to restart when this preference changes value.​2. app:isSilent
This is a boolean type attribute, which is by default set to true. That means that if you don't set this attribute and you DO set the package name to kill, it will restart the app you want without warning as soon as the value has been changed. If it is set to "false", upon value change a dialog will appear with app icon and test informing user that for this action to take effect an app restart is required. They can then choose to kill app now or cancel the dialog and kill it later.​3. app:rebootRequired
This is also a boolean type of preference which by default is set to false. If you set it to "true", upon preference value change a dialog will appear, informing the user that reboot is required for this action to take effect. good example for that is changing the default app intent to open on home button double click. That needs framework reload.
If rebootRequired is set to true and you ALSO set package name to kill, reboot takes preference. Package to kill will be ignored.​
Preferences - Part 2: Types of Preferences
1. Two state preferences (meaning - can be true or false)
MySwitchPreference & MyCheckboxPreference
Code:
[COLOR="Teal"][B] <!--Following category shows variety of two state preferences-->[/B][/COLOR]
<PreferenceCategory
android:title="Two stated preferences test category">
[COLOR="DarkGreen"][B] <!--Normal Switch preference-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MySwitchPreference
android:defaultValue="true"
android:key="normal_test_switch"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Normal test switch"/>
<!--Switch preference which will throw a dialog that app reboot is required-->
<com.wubydax.romcontrol.v2.prefs.MySwitchPreference
android:defaultValue="true"
android:key="kill_app_with_dialog_test_switch"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Kill app with dialog switch"
app:isSilent="false"
app:packageNameToKill="com.android.systemui"/>
[COLOR="darkgreen"][B] <!--Switch preference which will in ADDITION to actual work, also silently restart app with given package-->
<!--Note, that isSilent attribute is by default TRUE. So you don't need to specify it if you want silent app restart-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MySwitchPreference
android:defaultValue="true"
android:key="kill_app_silently_test_switch"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Kill app silently test switch"
app:packageNameToKill="com.android.contacts"/>
[COLOR="darkgreen"][B] <!--Switch preference which will throw a dialog that following it's action device reboot is required-->
<!--Please note, even if you specify the need to kill app, once the rebootDevice attribute is TRUE, kill app attributes are ignored-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MySwitchPreference
android:defaultValue="true"
android:key="reboot_required_test_switch"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Switch reminding of need to reboot"
app:rebootDevice="true"/>
[COLOR="darkgreen"][B]<!--We can use kill app on checkboxes as well. Same goes for rebootDevice-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MyCheckBoxPreference
android:defaultValue="true"
android:key="test_checkbox_with_kill_app"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Kill app checkbox"
app:isSilent="false"
app:packageNameToKill="com.android.systemui"/>
</PreferenceCategory>
FilePreference
Code:
<PreferenceCategory
android:title="File preferences">
[COLOR="darkgreen"][B]<!--File preference is a very special kind of preference, which works like switch but has different output.
Normal switch preference, like any two state preference, write boolean true/false into preferences.
In our app it also writes 1/0 into database.
File preference doesn't write into database. If it is switched on, it creates a file in our app directory in data.
That name of that file is what you set as key.
This is widely used by [user=1042140]@tdunham[/user] for global boolean needs in systemui.
Please refer to his guide about setting global boolean to see appropriate smali application for this preference.
This is most useful for mods in smali files where you do not have context access to get content resolver.
Because File class is native java class and checking for it's existence does not require android context.
File preferences can have attribute to kill app or reboot device.-->[/B][/COLOR]
[COLOR="darkgreen"][B] <!--This is a simple file preference. Note that once it's switched on, a file with the name identical to key is created in
/data/data/com.wubydax.romcontro.v2l/files
When it's switched off the file is deleted.-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.FilePreference
android:key="new_file"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="New file preference"/>
[COLOR="darkgreen"][B] <!--This file preferences upon change will prompt to kill app-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.FilePreference
android:key="another_file"
android:summaryOff="Disabled"
android:summaryOn="Enabled"
android:title="Kill app file preference"
app:isSilent="false"
app:packageNameToKill="com.android.systemui"/>
</PreferenceCategory>
2. Dialog preferences
ColorPickerPreferece
Custom attributes:
alphaSlider, hexValue - both booleans, TRUE by default
Code:
[COLOR="Teal"]<!--The following category demonstrates various ways of using ColorPickerPreference-->[/COLOR]
<PreferenceCategory
android:title="Color pickers test category">
[COLOR="DarkGreen"][B]<!--Normal color picker preference-->
<!--Please note, the [COLOR="Red"][U]hexValue and the alpha are there by default now[/U][/COLOR]. If you want to cancel them, you need to specify false-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ColorPickerPreference
android:defaultValue="#ffccdd"
android:key="test_color_preference"
android:title="Normal test color picker"/>
[COLOR="DarkGreen"][B]<!--Color picker preference without the alpha slider and without the hex value
You can set false to both or one of them-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ColorPickerPreference
alphaSlider="false"
hexValue="false"
android:defaultValue="#ffffff"
android:key="no_alpha_color_key"
android:title="Color picker with no alpha or hex"/>
[COLOR="darkgreen"][B]<!--Color picker preference with kill app option
Note, [U]you can also use rebootDevice attribute[/U], like with two stated preferences-->[/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ColorPickerPreference
android:key="app_kill_color_key"
android:title="Color picker with app kill"
app:isSilent="false"
app:packageNameToKill="com.android.systemui"/>
</PreferenceCategory>
MyListPreference
Custom attributes:
app:dependentValue - will enable you to set dependencies upon choosing selected value. If a dependent value is selected by user, the dependent preference will become disabled.
Code:
[COLOR="DarkGreen"][I]<!--Example of simple list preference with radio button items
You absolutely HAVE to set dafaultValue and it has to be one of your entryValues string arrays
You can use any of the following with kill app attributes or rebootDevice attribute
Note, that you can now use dependency on list preference.
Custom attribute app:dependentValue will allow you to decide which list item, if selected,
will set dependent preferences disabled.-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MyListPreference
android:defaultValue="20"
android:entries="@array/test_list_entries"
android:entryValues="@array/test_list_values"
android:key="test_list_key"
app:dependentValue="1"
android:title="Choose items from the list preference"/>
ThumbnailListPreference
Custom attributes:
app:dependentValue - will enable you to set dependencies upon choosing selected value. If a dependent value is selected by user, the dependent preference will become disabled.
app:drawableArray - references array which provides resources for the thumbnail images for each list item
app:entryList - references array of strings to provide names for actual list items
app:entryValuesList - references array of strings for the entry values to be written to preferences and database for selected list item
Code:
[COLOR="darkgreen"][I] <!--Thumbnail list preference is a special kind of preference which allows you to show preview of the selected image
This can be useful f.e. for setting custom bg to toggles in systemui
Needless to say you need to put the same images you put in systemui in Rom Control in drawables
And you need to create 3 kinds of arrays in arrays.xml file. 2 string arrays for entryList and entryValuesList and one simple array
for drawable references. You can see the arrays for the following preferences inside arrays.xml
You have to set default and the default has to be one of entryValuesList strings-->
<!--Example of simple Thumbnail preference with no additional attributes-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ThumbnailListPreference
android:defaultValue="1"
android:key="test_thumbnail_key"
android:title="Simple thumbnail preference"
app:drawableArray="@array/thumbnail_drawables"
app:entryList="@array/thumbnail_items"
app:entryValuesList="@array/thumbnail_values"
app:dependentValue="2"/>
[COLOR="darkgreen"][I]<!--Example of Thumbnail preference which calls to kill app upon selected item-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ThumbnailListPreference
android:defaultValue="2"
android:key="test_thumbnail_kill_app"
android:title="Kill app thumbnail preference"
android:dependency="test_thumbnail_key"
app:drawableArray="@array/thumbnail_drawables"
app:entryList="@array/thumbnail_items"
app:entryValuesList="@array/thumbnail_values"
app:isSilent="false"
app:packageNameToKill="com.android.systemui"/>
IntentDialogPreference
Custom attributes:
app:intentSeparator - to allow you to set the char which will separate the package name from activity name in the intent component name
app:showSearch - boolean attribute which determines whether search field will be available in the dialog window. By default it's TRUE. If you want no search, set to FALSE
Code:
[COLOR="DarkGreen"][I]<!--The following preference is a special preference that's called IntentDialogPreference
This preference allows you to choose an app from the list. it also conveniently includes search field
This preference writes into database what's called component name for specific system needs.
When we want to call an app in android, we need to provide some information as to which app we want to launch
and which activity inside that app we want to lunch.
Launching app by combination of those is called explicit intent. Explicit intent needs 2 things to run an app:
1. Package name
2. Activity or service name
This preference is most useful for launching an specific app based on info you can fetch from database
For example on double click on home key
Intent dialog preference puts the info for explicit intent in a string. First package name, then separator, then activity name
You can use any separator you want. The default separator is "##"
But as you can see in following example we set the separator to be forward slash "/"
The separator depends on how you build the mod in smali for your needs.
Any kill app or reboot device attributes are applicable here as well-->
[/I][/COLOR]
[COLOR="darkgreen"][I]<!--This specific IntentDialogPreference has defaultValue set to Settings app.
You DO NOT need to set default. Only if you want to. But it is in most cases not necessary and even not that good.
This is just an example. When you run this, you will see that the preference has an icon of the chosen app on the right
and a name of the app set as summary. When you choose a new app, those things change-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.IntentDialogPreference
android:defaultValue="com.android.settings/com.android.settings.Settings"
android:key="test_intent_with default"
android:title="Select Test App with default"
app:intentSeparator="/"/>
[COLOR="darkgreen"][I]<!--This IntentDialogPreference comes with no default and no separator. So default separator will be applied "##"
and it also has no search showing-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.IntentDialogPreference
android:key="test_intent_without default"
android:title="Select app, no default, no search, ## separator"
app:showSearch="false"/>
[COLOR="darkgreen"][I]<!--This preference will prompt to reboot device upon selection
This is useful if f.e. you use it to set default app to open when home button is double clicked
Reboot is advised but not necessary immediately. So user will be shown a dialog to let them know they need to reboot
And they can reboot immediately or later-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.IntentDialogPreference
android:key="test_intent_without_default"
android:title="Select app and reboot device"
app:intentSeparator="/"
app:rebootDevice="true"
app:showSearch="true"/>
MyEditTextPreference
Code:
[COLOR="DarkGreen"][I][B] <!--Edit text preference is a dialog preference that allows you to enter custom text-->[/B][/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.MyEditTextPreference
android:defaultValue="test"
android:key="test_edit_text_key"
android:title="Input custom text"/>
​
3. Special Preferences
OpenAppPreference
Custom attributes:
app:componentName - string type attribute to provide package name and desired activity name to open installed app. Please pay attention to instructions in code.
Code:
[COLOR="darkgreen"][B][I]<!--The following category shows usage of special preference we use to open an app based on component info
All you need to provide for this preference is package name and activity name separated by forward slash "/" like shown below
We will split the component info into components and check if the app is installed
if it's installed, we will show the app icon as preference icon and app name as title
If the app is not installed the preference is automatically removed from the list.
You can set your own summary to explain about the app.
If you wish to show a custom icon for that app shortcut or have custom title,
if you wish to use custom icon or custom title, like you would do normally with preference,
You are free to use android:title and android:icon attributes.
Our class will then use the items you chose instead of the application title and icon.
This WILL NOT affect the intent for opening application. It's a cosmetic measure for your convenience.-->[/I][/B][/COLOR]
<PreferenceCategory
android:title="Shortcut to apps preferences">
[COLOR="darkgreen"][B][I] <!--Example of simple app shortcuts. If those apps are not installed, the preferences will not show-->
[/I][/B][/COLOR] <com.wubydax.romcontrol.v2.prefs.OpenAppPreference
android:summary="Application to browse your files, including root files"
app:componentName="com.speedsoftware.rootexplorer/com.speedsoftware.rootexplorer.RootExplorer"/>
<com.wubydax.romcontrol.v2.prefs.OpenAppPreference
android:summary="Control samsung's toolbox, turn it on or off, choose available apps and rearrange them"
app:componentName="com.wubydax.toolboxsettings/com.wubydax.toolboxsettings.ToolboxSettings"/>
[COLOR="darkgreen"][B][I] <!--Example of OpenAppPreference with custom title and icon-->
[/I][/B][/COLOR] <com.wubydax.romcontrol.v2.prefs.OpenAppPreference
android:summary="Choose what app or shortcut to open when TW launcher is being swiped to the magazine page"
android:title="Shortcut to GearTWSwipe"
android:icon="@mipmap/ic_launcher"
app:componentName="com.wubydax.geartwswipe/com.wubydax.geartwswipe.ResetDialogActivity"/>
[COLOR="darkgreen"][B][I] <!--Open app preference with only cuctom title and the icon which is loaded from the app-->
[/I][/B][/COLOR] <com.wubydax.romcontrol.v2.prefs.OpenAppPreference
app:componentName="eu.chainfire.supersu/eu.chainfire.supersu.MainActivity-Material"
android:title="Chainfire's SuperSu App"
android:summary="Manage root permissions for apps and services"/>
</PreferenceCategory>
UriSelectionPreference
Code:
<PreferenceCategory
android:title="Select image preferences">
[COLOR="darkgreen"][B][I]<!--Select image preferences allow the user to select any image from the gallery.
The uri for that image will be written into the database
Android can fetch images based on their uri (universal resource identifier).
A type of uri that you all know is called URL, which is a web address.
Uri for database is the "address" of an item inside the database.
In android we have Media database, which hosts info about media items. In our case we are interested in images.
Upon clicking this preference a Gallery will launch, upon selecting image, it's uri will be written into database.
In your mods you can fetch the string, convert it to Uri and set that image as background to anything you want.
We use this method for setting custom image in our mod for background to notification panel-->[/I][/B][/COLOR]
<!--Those are examples of simple uri selection preference. The icon for them will be the selected image preview
You need to set title and key. That's it.-->
<com.wubydax.romcontrol.v2.prefs.UriSelectionPreference
android:key="test_image_selection_key_2"
android:title="Select Image 2"/>
</PreferenceCategory>
RunScriptPreference
Custom attributes:
app:scriptFileName - string type attribute to provide script name to run, including the .sh extension.
app:showConfirmDialog - a boolean type preference, dtetermining whether a warning dialog will be shown before executing the script. we have had this request for previous version, since users sometimes hit script preference by mistake and it executes immidiately. By default this boolean is TRUE. So for any script a warning dialog will show. Youc an set it to FALSE to execute without warning.
app:rebootOptions - enum type attribute:
Sometimes you will perform actions in script which will require a device reboot to take effect
For this purpose we created this attribute, which can take 3 values:
1. None - this is default. You do not need to specify "none". if you don't specify rebootOptions it will always be "none"
This means reboot is not required upon running script
2. Optional - this means that the execution of this script is ok without immediate reboot,
but for the action to take effect, reboot is required. if you set rebootOption to "optional",
upon successful script execution a user will be presented with a dialog.
A dialog has 2 buttons: reboot now or reboot later.
Use this option ONLY if reboot is required for action to take effect and reboot is not VITAL. Meaning no app will FC without reboot.
3. Imminent- sometimes you will want to run scripts which replace key system components, such as entire apk
or even jar files. When a script like that is executed, you want immediate reboot. Because other wise the app in question
can throw FC. Most of you from what we have seen, use reboot option for scripts like these at the end of the script.
You NO LONGER HAVE TO. We will handle the reboot for you ONLY if the script is executed successfully and "imminent" option was chosen.
It is nice to WARN the user that their phone will reboot after running the script.
That is why if you choose app:rebootOptions="imminent" a dialog will be shown to the user once they click on preference.
This dialog will warn them that upon script execution their device will reboot
If you use this option, once the script is done we will execute the reboot. Make sure you have your app in priv-app before testing this. It will need reboot permissions. Please read the gradle explanation 2 posts above, regarding those permissions.
DO NOT use "reboot" or "kill zygote" commands at the end your scripts. Do yourselves and your users a favour and stop using those all together.​​
Code:
[COLOR="darkgreen"][I][B]<!--Running scripts in rom modding is no silly business.
We need shell scripts for purposes that can vary from writing a line into a file on sd,
through replacing sound files and host files,
to as far as replacing entire apk and jar files.
Because shell scripts can vary in their complexity, we created a special preference that runs shell scripts.
The major component in this preference is the scriptName attribute. The script name should be given in full,
as string, including extension (.sh).
The code for the preference knows where your scripts are found. It will locate the script if it's found there
and execute it.
if script execution fails, a number is being shown. That means the exit code of a script is not 0.
That means something is wrong in the script.
If the script is executed properly, a toast will be shown saying "Executed successfully"-->[/B][/I][/COLOR]
<PreferenceCategory
android:title="Run script preferences">
[COLOR="darkgreen"][B][I]<!--This is the basic script preference. It will jujst run a script.-->[/I][/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.RunScriptPreference
android:title="Execute script with prompt"
app:scriptFileName="simple_test.sh"
android:summary="This action will throw warning dialog before executing script"/>
[COLOR="darkgreen"][I][B]<!--Because of the radical nature of running shall scripts with su,
We included a dialog which is shown when a user clicks on script preference
By default confirm dialog will be shown before executing eny script. If you wish to run a script without the warning dialog,
You need to specify the custom attribute that a dialog should not be shown.
We strongly encourage you to keep the dialog. It's better for your users to be sure they clicked on the right option-->[/B][/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.RunScriptPreference
android:title="Execute without prompt"
app:scriptFileName="simple_test.sh"
app:showConfirmDialog="false"
android:summary="This action will execute script without warning"/>
[COLOR="darkgreen"][I][B]<!--Script preference with optional reboot-->[/B][/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.RunScriptPreference
android:title="Script with optional reboot"
app:rebootOptions="optional"
app:scriptFileName="simple_test.sh"
android:summary="This action will write into a file on sd card and show dialog that reminds the user to reboot their phone at this time or later for the action to take effect"/>
[COLOR="darkgreen"][I]<!--Script preference with imminent reboot-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.RunScriptPreference
android:title="Script with imminent reboot"
android:summary="This action will run script which has reboot command at the end and warn user that reboot of device will follow the script execution immediately"
app:rebootOptions="imminent"
app:scriptFileName="simple_test.sh"/>
[COLOR="DarkGreen"][B][I] <!--We were asked by some developers to make a kill app option available for script preference
Therefore, you can also use the kill package attributes now, silent or with dialog,
for your script preferences.
The following RunScriptPreference will prompt killing contacts app f.e
P.s. you can set icons to your run script preferences like any other preference-->[/I][/B][/COLOR]
<com.wubydax.romcontrol.v2.prefs.RunScriptPreference
android:title="Execute and kill app + icon"
android:icon="@mipmap/ic_launcher"
android:summary="Upon finishing, this script preference will prompt a user to kill app, since we set the isSilent attribute to false"
app:packageNameToKill="com.android.contacts"
app:isSilent="false"
app:scriptFileName="simple_test.sh"/>
</PreferenceCategory>
ImageHeaderPreference
Custom attributes:
app:imageSource - reference type of attribute to set the image to show as header preference. The default size for image is width match_parent and height 200dp.
This is just one of those little things we made for fun, but it ended up being @tdunham 's favourite toy
Code:
[COLOR="DarkGreen"][I]<!--This is one of those little bonus thingies what we made for our beta-testers
and you all get to inherit it. It's a little preference class called ImageHeaderPreference
It allows you to choose and image as header for your preference screen.
Just to bring a little color and life into all those switches and checkboxes...-->[/I][/COLOR]
<com.wubydax.romcontrol.v2.prefs.ImageHeaderPreference
app:imageSource="@drawable/android"/>
Themes, About Us activity and changelog dialog
1. Themes:
1. There 2 built in themes: light and dark. In the navigation drawer, much like in previous version, you have a section under More options which is called "Set Theme".
2. Upon clicking it a dialog will pop up to allow theme selection.
3. The default theme is the light one. If you wish your default theme to be the dark one, please navigate to res/values/styles and find the following line (at the very bottom):
Code:
<integer name="default_theme">0</integer>
(yes, we put integer in styles (because we CAN), we're weird like that... LOL. It's for your convenience.​
4. To make the default theme the dark one, change 0 to 1.​
2. About Us activity - how to populate it:
1. Navigate to values/about_us_resources.xml
2. When you open it you have 3 sets of 3 arrays each. This idea is very similar to how you populated the navigation drawer items. Let's have a look:
Code:
<resources>
[COLOR="Teal"][B]<!--Contact info arrays-->[/B][/COLOR]
[COLOR="DarkGreen"][B][I] <!--In this array you will put the icons for contact information,
for example xda icon for your xda thread, site icon for your site, facebook icon and so on-->[/I][/B][/COLOR]
<array name="about_contact_us_drawables">
<item>@drawable/icon_2</item>
<item>@drawable/icon_1</item>
<item>@drawable/icon_3</item>
</array>
[COLOR="darkgreen"][B][I]<!--In this array you will put the titles for your contact info items. Keep the order consistent between all 3 arrays-->[/I][/B][/COLOR]
<string-array name="about_contact_us_text">
<item>Facebook</item>
<item>Our Site</item>
<item>XDA</item>
</string-array>
[COLOR="darkgreen"][B][I]<!--In this array you will put the titles for the URL strings that will open once a user clicked on the item-->[/I][/B][/COLOR]
<string-array name="about_contact_us_links" translatable="false">
<item>https://www.facebook.com/</item>
<item>https://www.google.com/</item>
<item>http://forum.xda-developers.com/</item>
</string-array>
[COLOR="teal"][B]<!--Team info arrays-->[/B][/COLOR]
<array name="about_team_drawables">
<item>@drawable/icon_5</item>
<item>@drawable/icon_6</item>
<item>@drawable/icon_1</item>
</array>
<string-array name="about_team_names">
<item>Master Yoda - wise and talented lead developer</item>
<item>Luke Skywalker - one handed theme master</item>
<item>Darth Vader - dark theme master</item>
</string-array>
<string-array name="about_team_links" translatable="false">
<item>https://www.facebook.com/</item>
<item>https://www.google.com/</item>
<item>http://forum.xda-developers.com/</item>
</string-array>
[COLOR="teal"][B] <!--Credits and thanks info arrays-->[/B][/COLOR]
<array name="about_credits_drawables">
<item>@drawable/icon_1</item>
<item>@drawable/icon_3</item>
<item>@drawable/icon_4</item>
<item>@drawable/icon_2</item>
<item>@drawable/icon_6</item>
<item>@drawable/icon_5</item>
</array>
<string-array name="about_credits_names">
<item>Star Trek - for being ultimately better than Star Wars</item>
<item>Jean-Luc Picard - for making us crave hot earl-grey tea even in the middle of the summer</item>
<item>Data - for running on the best rom. Google, we still are waiting for THAT android version</item>
<item>Janeway - for being a normal person and drinking black coffee</item>
<item>Q - for reminding us that you can live forever and still look great</item>
<item>Worf - for teaching us to love Klingons. It was NOT easy</item>
</string-array>
<string-array name="about_credits_links" translatable="false">
<item>https://www.facebook.com/</item>
<item>https://www.google.com/</item>
<item>http://forum.xda-developers.com/</item>
<item>https://www.facebook.com/</item>
<item>https://www.google.com/</item>
<item>http://forum.xda-developers.com/</item>
</string-array>
</resources>
3. As you can see from the code above it's very simple. Find images you want to use, You don't need to make them round. They will be made round on runtime.
4. Replace the demo information in our arrays with your own, including images reference, titles and links. Make sure the lenghts of 3 arrays in each category are equal.
5. You can make as many or as little items as you want. As long as the length of drawable array equals to length of titles array and equals to length of links array in single category.
6. All the magic is done in java for you. Just populate arrays and RUNNNN​
3. Changelog Dialog - how to populate it:
1. Navigate to /res/values/changelog_resources.xml
2. Inside you will find 1 string and 1 string array. Let's have a look:
Code:
<resources>
[COLOR="Teal"][B]<!--Do not forget to include this in any locale specific folders for translation-->[/B][/COLOR]
[COLOR="Green"][B][I]<!--In the following array put your changelog items
Take as many lines as you need.
Add as many items as you want or delete some if those are too many
This order is how they will appear in the dialog
Make any order you want from top to bottom-->[/I][/B][/COLOR]
<string-array name="changelog_items">
<item>Some changelog thing lkjh l lkjh slkjh lkjh s,mnb lkjhs lkjh poiuy slkjh</item>
<item>Another changelog thing ;lkj d;lkj ;lkjs ;lkj ;lkj s;lkj ;lkj s;lkj ;lkj ;lks ;lkj ;lkj</item>
<item>Some more changelog things</item>
<item>Some even more changelog thing</item>
<item>And another changelog thing ;lsj; lkjs ;lkj ; lkj;lsjk ;sklj s;lkj s;lk js;lkj s;lkj</item>
<item>How many changelog things</item>
<item>What a long changelog!!!</item>
<item>Is it twenty already?</item>
<item>Are we there yet?</item>
<item>Live long and prosper</item>
<item>So say we all</item>
<item>Patience you must have</item>
<item>Great scot!!!</item>
<item>No disassemble…</item>
<item>Almost there</item>
<item>Done with changelog</item>
</string-array>
[COLOR="green"][B][I] <!--This will be the dialog title.
Put your own rom version and name.
Have fun-->[/I][/B][/COLOR]
<string name="rom_version_for_changelog">build v1.0 6thgearrom</string>
</resources>
3. Fill and up with your own items. Enjoy!​
Backup and Restore functionality
Backup and restore is done on a background thread using a service. Once the service gets intent with certain action it performs the required activity and shuts down.
The service can be called with wither backup action or restore action. In each case it will act differently.
1. How does that work - BACKUP:
When a request for backup is passed to the service, it does several things:
1. Checks if on your sdcard there exists a folder called RomControl and checks if the folder contains subfolder backups. If they don't exist, they are being created.
2. In our data f folder in data/data/com.wubydax... we have a shared_prefs folder. Inside it we have preference xml files for all of your preferences.
3. We iterate through those files and read them line by line, and once they are read, we take the keys and read the actual database value for that key
4. Then we write those values with their corresponding keys into a new backup file
5. Each backup file has a new name. You can see how it's formed here:
Code:
String currentDate = new SimpleDateFormat(getString(R.string.backup_file_prefix_date_format), Locale.ENGLISH).format(Calendar.getInstance().getTime());
String fileName = currentDate + "_" + Build.DISPLAY;
String backupFileName = fileName + getString(R.string.backup_file_suffix);
File newBackupFile = new File(Constants.BACKUP_FOLDER_PATH + File.separator + backupFileName);
As you can see we use 3 components for name:
a. Current date and time up to munites
b. The display id from the build.prop
c. suffix RCBackup​
That is so the users can differentiate between different backups from different roms or versions​
6. It also backs up the file preferences (see the preference explanation post for that)
7. The service finishes and throws a toast that it's done and the file can be found in the backup directory​
2. How does that work - RESTORE:
1. During restoring action, the main activity closes. It also says so in the warning dialog which appears right before restore is activated.
2. We made it so to make sure no onPreferenceChangeListener is triggered for any of your preferences. We also want a clean restart of the activity once the restore is done, so all the items can be loaded from the database, which has been updated by the restore process.
3. During restore we read the selected backup file, break it into pieces and write the values to database. When the activity is reloaded, preferences read from databases and update their own values.
4. For file preferences, during restore process we delete the files saved previously and only create the ones contained in backup file.​​
reserved 8
reserved 9
reserved 11
reserved 12
This blows away the original version folks.
Cant wait for it to go live. And couldn't resist being the first poster as well.
tdunham said:
This blows away the original version folks.
Cant wait for it to go live. And couldn't resist being the first poster as well.
Click to expand...
Click to collapse
You are simply the best ???
Sent from my SM-G920F using Tapatalk
Wow. This is amazing. Thank you for your time and sharing it. It's just another treasure after v1.0.
Sent from my SM-G935F using Tapatalk
Waiting
Wooooow , loooong time waiting for this , now time for reading & starting ready for it xD , as usual thanks for ur awesome work , ???
thereassaad said:
Wooooow , loooong time waiting for this , now time for reading & starting ready for it xD , as usual thanks for ur awesome work , ???
Click to expand...
Click to collapse
Happy to see you here! Don't read yet. Only posts 1, 2, 3, 4 and 6 are finalized.
Sent from my SM-G920F using Tapatalk
Wow, I am loving how this version is going to handle killing apps. And about custom preferences I am a bit confused but I guess I should wait till it's out and see how it would work. Setting default_theme it's just mind blowing! Guys before the source is out I think it would be a good idea to try reading and understanding what is outlined in OP I didn't use to sign my rc but it's explained clearly how to do it in studio. :good:
WOW!
As I have said before, you and Wuby are the most precious thing to us, the ROM devs
What an incredible update!
Sure, I have a lot of work to do on rom control v2, but I have you on my side -that's a good thing hehe.
Amazing work! I am sure my users enjoy it as well.
Keep it up, but make some time for me too
Sent from my SM-G900F boosted by PhoeniX ROM

[TOOL] ADB-Overlay [2.2.2.0 - .Net 6]

Heyho together,
after my P9-Lite and P10-Lite toolkit i thought, it's time to build a more generic version. Here it is, the ADB-Overlay!
The main point of this project is to serve a GUI for ADB. Currently, there is a File-Explorer, Remote-Desktop, Shell interface and APK installer implemented. You can also READ the contacts if your device is rooted and has sqlite3 installed. But a picture tells more as 1000 words... So here is a preview of what you'll get.
{
"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"
}
But anyways, i'm not responsible for any damage done to your device! For example, if you delete some files/folders on root lvl etc.
Component Info
Remote-Desktop:
Left-Click = Touch
Right-Click = Swipe with duration
The keyboard is nearly fully supported, i have written a kind of WPF -> Android key-mapper. So even combos like SHIFT+A-Z, SHIFT+0-9, ALT+A-Z and ALT+0-9 should work. The base for the key-mapping is a 102 keys keyboard with en-GB or de-DE layout. If you have another setup, some keys may on other positions.
The screenshots will be created under "ADB-Overlay\Screenshots\Screenshot.yyyy-MM-dd_HHmmss.(bmp | gif | jpg | png | tiff | wmp)".
-
If the device is booted in the recovery, the Remote-Desktop is only a viewer, because the recoveries doesn't support "input tap x y" nor "input keyevent XXX".
Shell:
The input box supports CTRL-A-Z, so you'll have the ability to send for example CTRL+C to stop a remote process. If you want use Copy & Paste onto the input box, use the Right-Click menu.
Tested OS
Win 7 | 8 | 8.1 | 10 | 11 (32Bit/64Bit in VM-Ware)
Win 7 | 8 | 8.1 | 10 | 11 (64Bit Native)
Tested Devices
Android Emulator some Versions (min. 2.x) in AVD
Android x86
HTC Sensation -/ XE (non-/rooted)
HTC One M9 (non-/rooted)
Huawei P9 Lite (VNS-L21, 22, 23, 31, etc.) (non-/rooted)
Huawei P10 Lite (WAS-LX1A, etc.) (non-/rooted)
Huawei Mate 9 (THX to @Tecalote)
Huawei Mate 10 Lite (THX to @Chisetdel31260)
Huawei P9 (EVA-al10) (THX to @reynard1)
Sony Xperia X (THX to @FoxTheLegend)
Pixel 4 (THX to @squabbi)
Requirements
Android: min. 2.x
Platform: x86/x64 (Windows)
Frameworks: min. .NET 6 / .NET 6 Desktop Runtime x86/x64
(Installed ADB/Fastboot driver)
Download
Mirror: See attachments
Mirror #1: My FTP [USR/PW=ADB-Overlay]
Mirror #2: GoogleDrive
Mirror #3: Dropbox
Mirror #4: Mega
DO NOT MIRROR MY FILES! DO NOT COPY MY THREADS!
Bug-Tracker
If you can't use the SDK-Updater or the Version is 0.0, just close the ADB-Overlay delete the "platform-tools" directory and restart the ADB-Overlay.
If the device won't connect via W-/Lan, check which version of android you are running... the latest version "SP2A.220505.002, May 2022" seems to break "Developer settings -> USB-Debugging -> Debug over W-/Lan"... To get it working anyways, just open a cmd prompt in the "platform-tools" folder, connect your device via USB and execute the following command: "adb tcpip 12345" (or some other port). After that, you should be able to connect your device via W-/Lan.
App Freeze
If the ADB-Overlay freezes during startup or by connecting a rooted device, the solution is to update the su binary. I encountered this problem yesterday on an older device running Android N. After an update to Magisk Canary [build 21005] the problem was solved.
Changelog
DD.MM.YYYY | (A) = Added | (C) = Changed | (D) = Deleted | (F) = Fixed | (R) = Recoded | (U) Updated
----------------------------------------------------------------------------------------------------------------------------------------------------
30.04.2022 [2.2.2.0]
(F) The SDK updater.
27.04.2022 [2.2.1.0]
(F) A freeze which occured on some FTP-Servers which doesn't implement RFC 959 properly.
11.04.2022 [2.2.0.0]
(U) General improvements in terms of speed and connectivity.
(U) The FTP config is now AES-256 encrypted for better security.
29.11.2021 [2.1.0.0]
(U) To .Net 6
(U) General improvements in terms of speed and connectivity.
25.07.2021 [2.0.2.0]
(A) ADB-Sideload
(U) ADB and Fastboot binaries.
(F) Some transfer issues (Binary <-> Socket)
(F) The platform-tools updater.
12.01.2021 [2.0.1.0]
(F) All freezes on the Tree-/ListView.
(A) ColumnHeader sorting on the Explorer and Apk-Manager ListView.
(A) Sort options for all header not only Name, Size, Date and Type.
(C) Sorting happens now in the background (So no more freezes here too.).
.-Older changes-.
12.12.2020 [2.0.0.0 - .Net 5]
Switched to .Net 5.0
(F) FTP-Updater timeout issue
(C) Brotli compression to .Net native
17.09.2020 [1.18.46.0]
(A) sendrecv_v2 for Android 11
(A) Brotli compression for file transfers on Android 11
29.03.2020 [1.17.46.0]
(A) Cut (via Context-Menu and "Ctrl+X")
(A) Copy (by default and via Drag'n'Drop by holding "Ctrl" during drop)
(A) Move (via Drag'n'Drop by holding "Shift" during drop)
(NOTE: Move is now enabled for on-device, device-to-device, local-to-device and device-to-local transfers.)
(C) The copy window, it will now display "Copy" or "Move" depending on the current operation.
16.03.2020 [1.16.46.2]
(F) The updater buttons, now they are also disabled during an download/check.
15.03.2020 [1.16.46.1]
(F) File/Folder interaction with those which contains "\s _ - ' , * & ~ | < > ( ) [ ] { }" in their names.
07.03.2020 [1.16.46.0]
(C) The synchronous IO to fully asynchronous IO.
(A) The Edit-Window, this will temporary download the file and open it locally in an application defined for this file type or with the "OpenAs" dialog.
(C) The UI, buttons which can't be used are now "grayed out".
12.02.2020 [1.15.46.1]
(F) The re-connection bug on the FTP-View. (Which also caused the updater to fail.)
(F) The (2 sec) freezes after copy/delete/tar.
(C) The info bar, added the modify date.
31.01.2020 [1.14.46.0]
(F/A) The timestamps for access, changed, modify.
(C) The "Properties Window", added the mentioned fields and resized the height a bit.
(A) Create File on the FTP-View.
30.12.2019 [1.13.46.0]
(F) The FTP TLS/SSL problem, now all procedures (implicit/explicit) should work without problems. (I tested this the last days with multiple servers, also the proxy's socks4/a|5 should now work with TLS/SSL.)
(U) All 3 explorers, they relay now on an shared generic base explorer which implements most of the features for all 3 views. So it's guaranteed that all views will behave the same.
(U) All 3 explorer views, changed the spacing's and the "edit textbox" (on rename) a bit, so that they look a bit more like the default explorer.
(A) IComparable<T> and IEquatable<T> to all List-/TreeViewItems so you get a pre-sort during item parsing. (I thought it would work a bit nicer, but hey, now it's implemented^^)
(R) Optimized the item (file/folder) parser for both Android & FTP.
18.12.2019 [1.12.46.1]
(F) The broken SDK-Updater, where you saw in the log file a "BindingException".
(F) The "SocketException" on app close. Reason for this was, that i disposed the "DeviceMonitor" after i killed the adb-server, but the monitor tried to check in some cases (10 sec refresh rate) for changes, after the server was already down.
(A) The "remount" option for mounts to the properties window. (You'll get also a little warning, each time you attempt to remount a mount point.)
(C) Resized the properties and the updater windows a bit.
17.12.2019 [1.11.46.0]
(F) The remote desktop for 16-Bit devices.
(R) Root detection
(R) Mount detection (added support for Android 2.x)
(R) The properties view, as mentioned, there is now a more valuable overview.
14.12.2019 [1.10.46.0]
(A) A version banner to the title bar.
(R) Nearly the whole caching logic inside the local ,Android and FTP explorer.
(R) The mount ([Device]) overview, now you'll see all mounts returned from "mount" and the assigned "df" data, if available. (The next build will include a more valuable overview in the PropertiesWindow. Like the mount options etc.)
(R) The remote desktop, i moved the "color correction" inside the pixel-buffer copy process. This will save a lot of time and boost the FPS in my TWRP up to 80++ per sec.. (That was so much, that .Net even couldn't dispose the sockets so fast as i requested a new one... This ended in an waiting queue overflow... So i decided to limit the FPS to 30-40 this is enough to have a clean view.) - Also NOTE: BOOTED IN ANDROID, WILL DECREASE THE FPS TO 2-3 DEPENDING ON THE RESOLUTION OF YOUR DEVICE! THE ONLY SOLUTION FOR THIS IS, START ADB WITH ROOT RIGHTS. (I added a internal switch, which will detect if adb runs as root, if so, i don't relay on the frame-buffer-service of adb. Instead, i use the bare metal (/sys/class/graphics/fb0/) to get the correct buffer values and then i read directly from "/dev/graphics/fb0".) AGAIN, NOTE: THIS WILL NOT RAISE THE FPS UP TO 80++, BUT THE FPS WILL INCREASE UP TO 15-25.
11.12.2019 [1.9.46.1] (HotFix)
(A) The mistakenly removed overwrite protection on item rename. (Android)
(R) The Copy & Delete view, the media-scanner, if activated, will now only run once at the end of an copy or delete action.
(R) Sym-/Directory/File detection, there was in rare cases a wrong detection where a SymDirectory was treated as an SymFile.
(F) The "Create New Textfile" action. (Android)
10.12.2019 [1.9.46.0]
(F) An ArgumentNullException which was raised during "mount" parsing. (On the "device" view.)
(F) The renaming issue, where you got, "The element couldn't be renamed!", if the name hasn't changed.
(A) Windows shortcuts to the TreeView of the Windows explorer. (Even the original one hasn't that feature )
(A) Hiding the ".lnk" extension on any Windows shortcut.
(A) Internal auto updates to the remote explorers (Android/FTP). So you have a kind of "pseudo" FileSystemWatcher.
(A) The re-sorting of the items after an rename action.
(D) Some code duplication. (Saved all together ~12 kb)
(R) Unnecessary refreshes and replaced them with internal cache logic's.
02.12.2019 [1.8.46.0]
(F) An ObjectDisposedException which was sometimes raised after symlink parsing and/or file transfers.
(C) The channeling on the ADBSocket, from an ConcurrentDictionary to an simple array with locks, this increased the transfer speed.
(U) The dlls to the latest versions.
24.07.2019 [1.7.46.0]
(R) The config files, both, the config.xml and the config.ftp.xml got an structure update. The old/current config files will be migrated to the latest version. So there should be no data loss in any way.
(A) A version banner to the Android and FTP view
(C) The adb directory from "ADB-Overlay\adb" to "ADB-Overlay\platform-tools"
(A) The SDK-Updater
(A) Auto-SDK-Update - If activated, this will check once every 24h for an update, but only on startup of the ADB-Overlay. (NO Tasks or something)
Info
The updater will only check "https://dl.google.com/android/repository/repository-11.xml". This XML gets downloaded and parsed, if the "platform-tools" version is newer as the used one, you'll get an popup which offers the download for the latest version.
The Auto-SDK-Update is by default disabled.
28.06.2019 [1.6.46.0]
(F) A memory leak which occurred by removing a device (Android View -> Closing an tab)
(F) A memory leak which occurred by removing a server (FTP View -> Closing an tab)
(R) Improved the directory parsing speed
(A) A progress bar to the copy window (green during transfer and on completion | red on failure or cancellation)
04.06.2019 [1.5.46.0]
(C) The versioning:
1 = Major
5 = Minor
46 = Framework Version (4.6)
0 = Hotfix
(A) A few speed improvements to the Remote-Desktop.
(A) The updater/-menu
(A) Auto-Update - If activated, this will check once every 24h for an update, but only on startup of the ADB-Overlay. (NO Tasks or something)
Info
The updater will only check my FTP for a ".version" file. This gets downloaded and parsed, if the version is newer as the used one, you'll get an popup which offers the download for the latest version. (NO logs and NO telemetry!)
The Auto-Update is by default disabled.
28.05.2019 [0.0.0.5]
(A) The "APK Manager" to the Android -> Tools menu
(A) {<-} & {->} buttons to the addressbar
(A) The "Install" option to the remote explorer -> ListViewItem context menu (only shown if the item is a apk)
(R) Added the missing options to the APK Installer (e.g. Downgrade, Test-Package, etc.)
(R) Optimized the "symlink" parsing
01.05.2019 [0.0.0.4]
(F) An exception which was raised after you tried to open any "Tool" on an disconnected device.
(A) A Battery Monitor to the Android -> Tools menu
29.04.2019 [0.0.0.3]
(A) Remote-Viewer when booted in the recovery
(A) A screenshot format selector (bmp | gif | jpg | png | tiff | wmp) to the Remote-Desktop
(A) A color correction switch to the Remote-Desktop
(A) Links to the German forum post
20.04.2019 [0.0.0.2]
(F) An issue during item renaming - Reason was maybe the switch from .NET 4 to .NET 4.6, seems the UI updates on textboxes are no longer only on focus got/lost, instead they are now after any change.
(A) Contextmenu (Listview) -> New -> Text Document
(A) Replacements for "New Directory", "Group (New)", "Server (New)" to the german language, so you get now after such an action the correct "Neuer Ordner", "Neue Gruppe", "Neuer Server".
(C) The FTP Copy/Delete action, you can now close the control connection and leave only those windows open until they are done. Both, the Copy and Delete action using now their own connection which is no longer bound to the control connection.
(C) Moved the "Keep Alive" checkbox (FTP -> Servermanager -> Account) to FTP -> Servermanager -> Connection
13.04.2019 [0.0.0.1]
Initial release
Great job. my huawei mate 10 lite is recognized. currently my smartphone is on rom original stock rne - l21c432b340 emui 8.0 not rooted. and my PC is a windows 7 64.
Works for my Xperia X - and thanks for your help!
I'm flattered to be in your contacts screenshot I was still using your prototype you had sent to me years ago!
Works very well on my Pixel 4!
squabbi said:
I'm flattered to be in your contacts screenshot I was still using your prototype you had sent to me years ago!
Works very well on my Pixel 4!
Click to expand...
Click to collapse
Hey Bro
long time not seen. Hehe yeah the good old Multi-Explorer ;p - Still using it my self, it's more or less my playground before i implement things in this tool.
If you want and have some spare time we can modify this beauty. I also reworked nearly the whole AndroidCtrl.dll, there you have now solid filestreams, strongly typed FilesystemInfos (Like the one from the .NET fw) and lots of other handy stuff. Like framebuffer access in Android and recovery mode. I also implemented a ADBridge class which is an instanced wrapper for the 2 static ADB classes (binary/socket).
Best Regards,
Sebastian
this is what im looking for a while
Thank you very much
here is some suggestion
1.better ui
2.edit build prop in the realtime
btw my phone is Huawei P9(eva-al10) rooted android 8.0 work very well
k1ll3r8e said:
Hey Bro
long time not seen. Hehe yeah the good old Multi-Explorer ;p - Still using it my self, it's more or less my playground before i implement things in this tool.
If you want and have some spare time we can modify this beauty. I also reworked nearly the whole AndroidCtrl.dll, there you have now solid filestreams, strongly typed FilesystemInfos (Like the one from the .NET fw) and lots of other handy stuff. Like framebuffer access in Android and recovery mode. I also implemented a ADBridge class which is an instanced wrapper for the 2 static ADB classes (binary/socket).
Best Regards,
Sebastian
Click to expand...
Click to collapse
Sounds great! I'm looking to get back into toolkit making later this year, I'm keen to see the improvments to your library! :good:
Great job. we can navigate and copy files efficiently.
Only one thing is missing. Why not keep file timestamp for last access and modifie dates? or let us choose the option to keep it or not.
skyrail01 said:
Great job. we can navigate and copy files efficiently.
Only one thing is missing. Why not keep file timestamp for last access and modifie dates? or let us choose the option to keep it or not.
Click to expand...
Click to collapse
Heyho,
which Android version are you using and on which action (pull/push) does the timestamps get lost?
Normally i preserve the timestamps but on some Android versions the "timestamp" field in the ADB-Protocol is ignored.
Maybe i can set the timestamps on an other way, but therefore i need to know the version.
Regards,
Sebastian
PS:
Some code where i set the timestamps
Upload
Code:
public void Close(DateTime fileCreationTime)
{
if (_ch?.IsConnected ?? false)
{
if (CanWrite)
{
int o = 0, w;
byte[] d = new byte[8];
d.SetUInt32LE((UInt32)SyncCmd.DONE, 0);
d.SetUInt32LE(ToUnixTime(fileCreationTime), 4);
//...
}
_ch.Close();
}
}
Download
Code:
//...
using (FileStream dfs = destination.Open(FileMode.Create, FileAccess.Write))
{
using (AFileStream sfs = OpenRead())
{
sfs.CopyTo(dfs, DMAX, msg, cancellationToken);
ct = sfs.CreationTime;
}
}
//...
if (msg.State == TransferState.Done)
{
destination.CreationTime = ct;
transferEventHandler?.Invoke(Client.ID, new FileTransferEventArgs(Client.ID, msg));
return true;
}
//...
Thank you really great program keep it up
Hey,
I am operating under lineageOS 16 on Galaxy S5 (klte), using adb 1.0.39 on windows 10 64-bits, either via wifi or usb connect.
I check file dates under Windows, in console mode with far manager (M: last write time, C: creation time, A: last access time).
I am using linux command ls -l under adb shell from Windows command line to list files pushed to Android.
When pushing files from Windows to Android, only M is preserved, with a 2 hours offset (ES file explorer tells it is modified date) Maybe daylight issue or bad timezone.
When pulling files from Android, only C is preserved
When I pull back to Windows, files pushed to Android, all original date is lost.
But I am pretty sure we can preserve last access, modified and creation date as I could see Adbexplorer (another project) pull files keeping M and A (adb pull -a).
Hope I give you enough details.
k1ll3r8e said:
Heyho,
which Android version are you using and on which action (pull/push) does the timestamps get lost?
Normally i preserve the timestamps but on some Android versions the "timestamp" field in the ADB-Protocol is ignored.
Maybe i can set the timestamps on an other way, but therefore i need to know the version.
Regards,
Sebastian
PS:
Some code where i set the timestamps
Upload
Code:
public void Close(DateTime fileCreationTime)
{
if (_ch?.IsConnected ?? false)
{
if (CanWrite)
{
int o = 0, w;
byte[] d = new byte[8];
d.SetUInt32LE((UInt32)SyncCmd.DONE, 0);
d.SetUInt32LE(ToUnixTime(fileCreationTime), 4);
//...
}
_ch.Close();
}
}
Download
Code:
//...
using (FileStream dfs = destination.Open(FileMode.Create, FileAccess.Write))
{
using (AFileStream sfs = OpenRead())
{
sfs.CopyTo(dfs, DMAX, msg, cancellationToken);
ct = sfs.CreationTime;
}
}
//...
if (msg.State == TransferState.Done)
{
destination.CreationTime = ct;
transferEventHandler?.Invoke(Client.ID, new FileTransferEventArgs(Client.ID, msg));
return true;
}
//...
Click to expand...
Click to collapse
skyrail01 said:
Hey,
I am operating under lineageOS 16 on Galaxy S5 (klte), using adb 1.0.39 on windows 10 64-bits, either via wifi or usb connect.
I check file dates under Windows, in console mode with far manager (M: last write time, C: creation time, A: last access time).
I am using linux command ls -l under adb shell from Windows command line to list files pushed to Android.
When pushing files from Windows to Android, only M is preserved, with a 2 hours offset (ES file explorer tells it is modified date) Maybe daylight issue or bad timezone.
When pulling files from Android, only C is preserved
When I pull back to Windows, files pushed to Android, all original date is lost.
But I am pretty sure we can preserve last access, modified and creation date as I could see Adbexplorer (another project) pull files keeping M and A (adb pull -a).
Hope I give you enough details.
Click to expand...
Click to collapse
Heyho,
THX for that info, i'll check the "adbd" source which LOS uses, maybe there is the prob. According to "adb pull -a" i'll also have a look at the adb source, because i think they do some "touch" stuff. Because the ADB-Protocol it self only supports creation/last modified time. In the source is a another "struct" for "STA2" (stat 2) command. But i have never seen a adb binary which supports this. (All binaries use the "STAT" command.)
EDIT 1:
Just checked the adb source again, seems they changed it a bit...
(This is the current STAT (v1) header)
Code:
# cmd name STAT or STA2 // 4 bytes
st->st_mode = msg.stat_v1.mode; // 4 bytes
st->st_size = msg.stat_v1.size; // 4 bytes
st->st_ctime = msg.stat_v1.mtime; // 4 bytes
st->st_mtime = msg.stat_v1.mtime; // 4 bytes
My HTC-One M9, Sensation, VM-Ware (Kitkat - Nougat) none of them has a 20 byte header. ALL of them return a 16 byte header.
Code:
CMD // 4 bytes
Mode // 4 bytes
Size // 4 bytes
CTime // 4 bytes
So it seems the protocol is highly inconsistent... I'll check how much time gets lost by calling touch on each file, because, currently i open a sync channel via an smart-socket, transfer the file and read all data provided by the protocol header. This is really fast, but if i have to spin up each time another channel to get a shell for the touch, this will increase the time each copy needs. Because, a shell depending on the version (v1, v2), has a lot checks you need to perform, specially the shell_v2 because it's like a ssh protocol.
EDIT 2:
Just for completeness, i'm pretty sure your device also sends only a 16 byte header for the stat v1 command, because:
(This is a cut of my implemented "Stat(byte[] bytes)" class)
Code:
if (c == (uint)SyncCmd.STA2 && bytes.Length >= 72)
{
ID = SyncCmd.STA2;
Error = bytes.GetUInt32LE(4);
Dev = bytes.GetUInt64LE(8);
INode = bytes.GetUInt64LE(16);
Mode = bytes.GetUInt32LE(24);
NLink = bytes.GetUInt32LE(28);
UID = bytes.GetUInt32LE(32);
GID = bytes.GetUInt32LE(36);
Size = bytes.GetUInt64LE(40);
ATime = bytes.GetInt64LE(48);
MTime = bytes.GetInt64LE(56);
CTime = bytes.GetInt64LE(64);
}
else if (c == (uint)SyncCmd.STAT && bytes.Length == 16)
{
ID = SyncCmd.STAT;
Mode = bytes.GetUInt32LE(4);
Size = bytes.GetUInt32LE(8);
CTime = bytes.GetUInt32LE(12);
}
As you can see, the both structures differ in there field order, if your device would send a 20 byte header, the test (bytes.Length == 16) wouldn't match. And you couldn't download a file.
EDIT 3:
After playing a while with "stat" and "touch" on some Android versions, i decided to rely on those functions. The next build should restore and write the correct timestamps.
EDIT 4:
Well, setting timestamps on the SD-Card doesn't work, also, setting timestamps on the "internal" SD-Card doesn't work either. Seems that it's related to the underlying FS. If i try to set the timestamp on an ext4 partition, it works. So it doesn't make sense to rewrite the push/pull functions because the return of touch for 99% of the time will be "touch: '/sdcard/TWRP/test.pdf': Operation not permitted". So it's simply a time waste during the copy procedure. BUT, i'll implement it at least for the download, so u'll get the correct timestamps on Windows.
EDIT 5:
Added a screenshot of the new "Properties Window" which also proves that the download timestamps are now correct.
(Btw. C doesn't mean created - it means changed)
Code:
stat /sdcard
File: `/sdcard' -> `/storage/self/primary'
Size: 21 Blocks: 0 IO Blocks: 512 symbolic link
Device: 1h/1d Inode: 4432 Links: 1
Access: (777/lrwxrwxrwx) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 1970-01-01 01:00:00.000000000
Modify: 1970-01-01 01:00:00.000000000
Change: 1970-01-01 01:00:00.360063176
Little update about the "creation time". After a bit research i found this post on Stack Exchange, there is explained that the so called "birth time" is stored since ext4 as part of the INode field. But it seems you need a special version of "stat" to read this info, it's called "statx". But so far i could see, Android doesn't support this feature, maybe some kernel does but it seems that it's more the rare case.
Regards,
Sebastian
Thanks for the update!
I was wondering what could be causing a small delay in copying files over, once the progress finishes, the transfer dialog remains frozen for a 1-2 seconds. I'm copying over a photo, so around 2MB.
squabbi said:
Thanks for the update!
I was wondering what could be causing a small delay in copying files over, once the progress finishes, the transfer dialog remains frozen for a 1-2 seconds. I'm copying over a photo, so around 2MB.
Click to expand...
Click to collapse
Heyho ,
yup i still working on it. It seems that the "Task.Delay()" isn't performed inside the Task itself, instead it's executed on the main thread. The reason for the freeze is, that i try to show the last result, otherwise the copy window would close immediately after the last element and you couldn't see if it's transferred or not. So i keep it like windows, wait 1,5-2,5 sec before closing the window.
The delay you might feel extremely is the "Media-Scanner". It runs on the end of each copy/delete action, the reason for this is, that files pushed/copied by adb are not reported to the MTP interface. So you couldn't see those files if you connect your device after such an adb copy via MTP. Also files/folders deleted by adb are also not reported to the MTP interface. So you will see those elements via MTP if you don't perform manually the "Media-Scanner" lookup. - But if you work only with adb for example, you could turn the "Media-Scanner" off. All device based explorers and of course adb will see those files/folders at any times. (But if you need those files/folders for exchange you should keep the "Media-Scanner" on )
EDIT:
This is executed for every file which is copied/pushed/deleted.
Code:
_adb.Device.Manager.ActivityManager.Broadcast("android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-a", string.Concat("-d 'file://", remotePath, "' > /dev/null"));
EDIT 2 (a bit off-topic):
You could also simply use the "Media-Scanner" with my AndroidCtrl.dll. The calls are:
Code:
//"_adb" is a instance of "ADBClient"
_adb.Device.IO.MediaScanner.CreateScanList(string remoteDirectory, MediaScanMode mode);
_adb.Device.IO.MediaScanner.CreateScanList(string remoteDirectory, MediaScanMode mode, CancellationToken cancellationToken);
_adb.Device.IO.MediaScanner.CreateScanList(string remoteDirectory, IList<string> files, MediaScanMode mode, CancellationToken cancellationToken);
_adb.Device.IO.MediaScanner.ScanDirectory(string remotePath, MediaScanMode mode);
_adb.Device.IO.MediaScanner.ScanDirectory(string remotePath, MediaScanMode mode, CancellationToken cancellationToken);
_adb.Device.IO.MediaScanner.ScanDirectory(IEnumerable<string> remotePaths, MediaScanMode mode);
_adb.Device.IO.MediaScanner.ScanDirectory(IEnumerable<string> remotePaths, MediaScanMode mode, CancellationToken cancellationToken);
_adb.Device.IO.MediaScanner.ScanFile(string remotePath, MediaScanMode mode);
_adb.Device.IO.MediaScanner.ScanFile(IEnumerable<string> remotePaths, MediaScanMode mode);
_adb.Device.IO.MediaScanner.ScanFile(IEnumerable<string> remotePaths, MediaScanMode mode, CancellationToken cancellationToken);
_adb.Device.IO.MediaScanner.ScanObject(ITransferMessage message, MediaScanMode mode);
EDIT 3:
Found the bad boy, seems "Task.Delay()" only works when used in "async" context. Now the "freeze" is gone, you can move the window until it vanishes. So, in the next update those "freezes" are gone.
---
Little Update:
@squabbi
The next update includes a little editor as suggested by @reynard1. A screenshot can be found as attachment.
Regards,
Sebastian
k1ll3r8e said:
**snip**
EDIT 3:
Found the bad boy, seems "Task.Delay()" only works when used in "async" context. Now the "freeze" is gone, you can move the window until it vanishes. So, in the next update those "freezes" are gone.
---
Little Update:
@squabbi
The next update includes a little editor as suggested by @reynard1. A screenshot can be found as attachment.
Regards,
Sebastian
Click to expand...
Click to collapse
Woohoo! Thanks for digging into it! I'm glad you found the culprit haha.
Looking forward to that editor feature! Do you know if it's possible to integrate with Windows Explorer? It's probably a little harder, but something like how WinSCP can drag files from the remote to a local Explorer window.
If that's a little difficult, would this be possible to implement? If I drag and drop a folder/file onto the local pane, it will change directory (and highlight the file if a file was dragged onto the local pane). Just to make it easier to work with folders I have already open.
Still using Windows 7?
squabbi said:
Woohoo! Thanks for digging into it! I'm glad you found the culprit haha.
Looking forward to that editor feature! Do you know if it's possible to integrate with Windows Explorer? It's probably a little harder, but something like how WinSCP can drag files from the remote to a local Explorer window.
If that's a little difficult, would this be possible to implement? If I drag and drop a folder/file onto the local pane, it will change directory (and highlight the file if a file was dragged onto the local pane). Just to make it easier to work with folders I have already open.
Still using Windows 7?
Click to expand...
Click to collapse
Heyho
Yes its definatly possible, we need to use the so called "VirtualFileDataObject". I tried to implement it some time ago, but doesn't worked as expected. But i'll give it another try.
-
Yup, i still use Win 7 as my main system, but i have some VMs running, like my Debian server which serves the documentation and some test sites for my php projects, a few Android x86 Versions and of course a legit Win10 installation to test If everything works.
*Never change a running system! - Currently my main hdd has a uptime of 2689 days with 216 restarts, i think that tells a lot *
---
Little Update:
As the screenshot shows, the editor is working fine so far. (Added also a few more controls.) The only problem i still have is, that if ADB doesn't run as root you can't edit for example the "build.prop". Because ADB can't write the file directly back, so i need to build a kind of "tmp" file. The next problem will be, that you (the user) have to remount the mount point, before you start editing those "root" and "write protected" files. There is also a problem with "binary" files, because the "RichTextBox" screws up when it gets "binary to ASCII/UTF8" transformed data, which ends in an app freeze... So i have to check on some way if the stream contains really text-data, the file extension doesn't help here much because, you know, linux uses also a lot of txt files without any extension.
Update 2:
Just got the "binary" files running... With a super BIG drawback, 248 kb (4069 rows) text results in 269,364 mb memory utilization by the "RichTextBox". - The prob here is, that the ADB filestream doesn't support seek, so i need to load the whole doc in one, which is quiet to much for the "RichTextBox"...
Update 3:
Soo, i wrote a kind of paging for the "RichTextBox" which works so far really nice, at least when it comes to the memory (even during scrolling, with free running wheel, only 15 - 27 mb increase), there is now a fixed amount of rows (40) which will be shown, all other rows are hidden from the "RichTextBox". This opens a few new issues^^ - Currently there is no selection possible which goes beyond the 40 rows. Also insert and delete are a little challenge because, i need to "overwrite" the default behavior with the some "PreviewKeyDown/etc." events... - Looks all a bit hacky, but lets see if it works in the end.
Update 4:
Well, the "RichTextBox" is out of the race^^ - It triggers events more or less random instead when you expect it, it removes blank lines (for example you have 3x "\n", this gets wrapped to 1x "\n") and the best, you remove "\r" during stream reading and the RTB adds it again, also random (some paragraphs get an "\r" some not). Editing text in a solid way without losing something isn't possible with this thing... So i'll try the "TextBox".
Last Update before release:
So, after testing the "RichTextBox" and "TextBox" i ask myself why those controls are there^^. Both can't edit text with more than a few hundert lines, the "TextBox" is at least much better as the "RichTextBox" but it also screws up when i comes to more as 250 kb text. So the "Editor" will be one of your installed applications. I add a little tool window, which offers the temporary download to the windows temp folder, after that i launch the windows "OpenAs" dialog that you can choose the editor you want. Also, i'll attach a "FileSystemWatcher" to the file that the upload automatically happens when you press save in your editor.
Little Info:
It take a few more days for the "edit" update, because i started also to implement the TAP pattern, this increased for example the download speed by factor 6. But to implement it the right way, i have to rewrite a lot of code in the AndroidCtrl.dll and AndroidCtrlUI.dll.
Regards,
Sebastian
k1ll3r8e said:
Heyho
Yes its definatly possible, we need to use the so called "VirtualFileDataObject". I tried to implement it some time ago, but doesn't worked as expected. But i'll give it another try.
-
Yup, i still use Win 7 as my main system, but i have some VMs running, like my Debian server which serves the documentation and some test sites for my php projects, a few Android x86 Versions and of course a legit Win10 installation to test If everything works.
*Never change a running system! - Currently my main hdd has a uptime of 2689 days with 216 restarts, i think that tells a lot *
** snip **
Click to expand...
Click to collapse
That'll be great to see haha, and that does make sense keeping your system as is, if it works, it works.
Thanks for your hard work in checking out what's best for the new edit function. Maybe there's a library out there that can implement a text viewer better? I'm not familiar with WPF libraries, or how many there are.
squabbi said:
That'll be great to see haha, and that does make sense keeping your system as is, if it works, it works.
Thanks for your hard work in checking out what's best for the new edit function. Maybe there's a library out there that can implement a text viewer better? I'm not familiar with WPF libraries, or how many there are.
Click to expand...
Click to collapse
Heyho,
i have had a look on Avalon Texteditor but on StackOverflow is also a discussion about how to open a file bigger than 20 mb. It seems WPF is not that great for such things. I found also another one, written by a lonely dev like me , but it's not maintained since 7 years. So the best way might be, open a installed App which is well designed for that purpose.
A bit off-topic
I nearly finished the TAP implementation for the AndroidCtrl.dll, so far it brought a great speed increase. Also, it consumes less CPU time, for example the remote desktop uses only 3-7% on an Intel I5 with 32 GB memory (but up to 36% on an single-core Intel Pentium M with 1,5 Ghz and 1 GB memory - my old well working Laptop, also with Win7 ). So you might be happy to see all the new "real async" overloads in the lib. (I implemented all from scratch, so there is NO Task.Run() or Task.StartNew() in those functions.)
Edit:
Soo, after a few horrible days, the TAP pattern is now fully integrated! But there is still a little issue with the Remote-Desktop recovery viewer. It seems that everything got a speed boost except the recovery viewer, the viewer is currently nearly 4x slower as before... After i fixed this last problem, i'll release the new asynchronous version.
Regards,
Sebastian

Categories

Resources