[Q] Can i add Activity to Array List? - Java for Android App Development

Can i add Activity to Arraylist (Java- Eclipse/android Studio) ? If i can, can you tell me how?

ArrayList<Activity> activities = new ArrayList<>();
activities.add(someActivity);
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Any Type In ArrayList
Basically objects of any type of class can be added to an ArrayList<Type> be it activities, intents etc. As ArrayLists are generic containers, it can be inferred from the name itself that it can be used for storing any type of data.

You can get your activity classes before hand without storing them into an array like this:
Code:
ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
int sizeStack = am.getRunningTasks(2).size();
for(int i = 0;i < sizeStack;i++){
ComponentName cn = am.getRunningTasks(2).get(i).topActivity;
Log.d("", cn.getClassName());
}

Lol please don't do that in a published app. You can in fact even store activities in a hashmap but it's really not user friendly and you would end up with dupe activitys that takes up unnecessary memory.

Related

How to execute arbitrary code...

Dear all,
I want to publish here one very very simple method how you can execute arbitrary code in your applications.
This method can be used to protect your software with runtime decryption\encryption mechanisms.
For example, your license checking function can be stored in the exe-file somehow encrypted and you'll be able to decrypt it in runtime end execute.
Using this method you can even encrypt all your application and decrypt only necessary functions just before you want to execute them.
Of course you should understand that any security mechanisms sooner or later will be cracked, but our goal is not to create non-breakable security, but to make cracking process more expensive then buying a license.
So, the idea is simple: we can prepare some buffer in the application and in the runtime copy there code we want to execute.
Here is source code:
Code:
/*
After compilation it is necessary to change flags of .mysec
from 60000020 (Code Execute Read) на E0000020 (Code Execute Read Write)
Just open exe-file, search for 0x20 0x00 0x00 0x60 after text ".mysec"
and change it to 0x20 0x00 0x00 0xE0
*/
#include <windows.h>
// turn off optimiztions
#pragma optimize("", off)
// define our code segment
#pragma code_seg(".mysec")
// let's allocate some place in our new segment
__declspec(allocate(".mysec")) BYTE pBUF[100];
// put functions to the new segment (not necessary!)
int func1(int i)
{
return i*2;
}
int func2(void) // just fake function. we'll need it to find size of func1
{
return 5;
}
// turn on optimizations
#pragma optimize("", on)
// switch back to .text segment
#pragma code_seg()
// define pointer to function
typedef int (*pfn_t)(int i);
int _tmain(int argc, TCHAR* argv[])
{
func2(); // not so necessary, but linker might remove unused functions... :-\
// here we're copying code of func1 into the buffer :)
// in fact, here should be some procedure decrypting necessary
// code into our buffer, but to simplify the example, I'll
// just copy one of existing functions int the buffer
// and then execute it
memcpy(pBUF, &func1, (int)&func2 - (int)&func1);
int a = ((pfn_t)(void*)pBUF)(4); // execute
// show result
wchar_t pBuf[20] = {0};
wsprintf(pBuf, L"a = %d", a);
::MessageBoxW(0, pBuf, L"tst1", MB_OK);
return 0;
}
I'll also attach the compiled application for those who think it won't work.
Thank you!
Best regards,
efrost

Listing apps

A friend of mine is stuck in the app we're doing, and he's getting certain trouble:
Code:
//This lists installed apps
final ListView list1 = (ListView) findViewById(R.id.list1);
ArrayList results = new ArrayList();
PackageManager pm = this.getPackageManager();
Intent inte = new Intent(Intent.ACTION_MAIN, null);
inte.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> list = pm.queryIntentActivities(inte, PackageManager.PERMISSION_GRANTED);
for (ResolveInfo rInfo : list) {
results.add(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
}
list1.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results));
His questions are: How I can do that instead of showing the icons name? If he tries
Code:
results.add(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
it shows "[email protected]"
And how could one run the application by clicking on the list?
Thanks in advance!
Not really sure why you're doing it that way but should be easier like this:
Code:
PackageManager pkgMgr = getPackageManager();
List< ApplicationInfo > list = pkgMgr.getInstalledApplications(0);
int len = list.size();
for (int index=0; index < len; index++)
{
ApplicationInfo content = list.get( index );
String pName = content.packageName;
String appLabel = pkgMgr.getApplicationLabel( content );
Drawable icon = pkgMgr.getApplicationIcon( content );
//do whatever you need with properties/icons to here
}

[Q] app to calculate RAM,CPU usage and other stuffs

hey xda people...i am pretty new to android development.. (have started building some basic apps! )
i was planning to build an app that can:
1.calculate RAM usage by the system
2.CPU usage by the system.
3.number of ongoing processes in the system.
4.kill unused running background applications to free space.
can anyone please provide the java source code for the above?
thanks in advance
Wait a moment. I'll code your new app in a minute.
thanks m eagerly waiting ...
To get free RAM:
Code:
public Integer getFreeRAM() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
Integer mem = (int) (mi.availMem / 1048576L);
return mem;
}
To get total RAM you can parse
Code:
/proc/meminfo
To get CPU Load/Usage parse
Code:
/proc/stat
To get Running apps use something like:
Code:
ActivityManager actvityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> procInfos = actvityManager.getRunningTasks(1000);
or you could execute ps or top and parse output
Hope it helps
by a fellow developer: https://play.google.com/store/apps/...mNvbS5jZ29sbG5lci5zeXN0ZW1tb25pdG9yLmxpdGUiXQ..
Take a look at it should be helpful at what you want to achieve.
pedja1 said:
To get free RAM:
Code:
public Integer getFreeRAM() {
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
Integer mem = (int) (mi.availMem / 1048576L);
return mem;
}
To get total RAM you can parse
Code:
/proc/meminfo
To get CPU Load/Usage parse
Code:
/proc/stat
To get Running apps use something like:
Code:
ActivityManager actvityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> procInfos = actvityManager.getRunningTasks(1000);
or you could execute ps or top and parse output
Hope it helps
Click to expand...
Click to collapse
thanx for rplyin...
i have already built an app to calculate available ram
can u please elaborate a bit more about the parsing issue??
because i am unable to get what u are saying
Arnab B said:
thanx for rplyin...
i have already built an app to calculate available ram
can u please elaborate a bit more about the parsing issue??
because i am unable to get what u are saying
Click to expand...
Click to collapse
Files /proc/stat and meminfo contains information you need. You just have to read from those files. For ram its easy, first line from proc/meminfo is what you need.
For CPU load check here:
http://stackoverflow.com/questions/3118234/how-to-get-memory-usage-and-cpu-usage-in-android
Sent from my Evo 3D GSM using Tapatalk 2
to get values you need to let the app read the file and import the content in an array (if contains multiple values) or in a simple String.
Code:
File yourFile = new File("/complete/path/to/the/file");
FileInputStream fin = null;
try {
fin = new FileInputStream(yourfile);
byte fileContent[] = new byte[(int)yourfile.length()];
fin.read(fileContent);
String s = new String(fileContent);
}
catch (FileNotFoundException e) {
System.out.println("File not found" + e);
}
catch (IOException ioe) {
System.out.println("Exception while reading file " + ioe);
}
finally {
try {
if (fin != null) {
fin.close();
}
}
catch (IOException ioe) {
System.out.println("Error while closing stream: " + ioe);
}
}
String[] values = s.split("\\s+");
Note that if you need to retrieve a specific value, the first item in the array is called "0".
for example, if we read the file /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies , this is the content:
Code:
51000 102000 204000 340000 475000 640000 760000 860000 1000000 1100000 1200000 1300000 1400000 1500000
so:
"s" will be:
Code:
[B]s[/B] = 51000 102000 204000 340000 475000 640000 760000 860000 1000000 1100000 1200000 1300000 1400000 1500000
note that, s.split("\\s+");, will split the string where there are "spaces" (" ")
and "values" will be:
Code:
[B]values[/B] = {51000;102000;204000;340000;475000;640000;760000;860000;1000000;1100000;1200000;1300000;1400000;1500000}
so, if you need to call one item from the "values" array, you can simply do it by calling values[position] , where "position" it's an integer from 0 ( = 51000) to the max lenght of your array.
if you need to convert these numbers in Integers to make some math operations you can do this using:
Code:
int val = Integer.parseInt(values[position]);
simple

[Library] Cmd library: Execute Your Java Codes With Root Access Privileges

Synopsis:
Have you ever wanted as root apps developer to use your favourite Java codes instead of bash/shell commands?
Have you grown tired of Runtime.getRuntime.exec("su") and ProcessBuilder("su").start()?
I did and still do, that's why I've been searching for a solution for my problem until I found out in AOSP source code that some of *.java files run with root access, tracking the way they execute them with root access led me to make this simple library.
Description:
Cmd library -short for Command- is an open source (licensed under Apache licence V2) that allows you to execute java commands with root access privileges by passing package name, full class name and whether your app is a system app or not in just two lines of codes.
For instance, suppose you want to flash a *.img recovery image, the first thing comes to your mind is this code:
Code:
busybox dd if=/path/to/recovery.img of=/path/to/recoveryPartition
lets say /sdcard/recovery.img is the file path and /dev/block/mmcblk0p12 is the partition (Samsung GALAXY Ace Plus GT-S7500)
Here is how to implement it:
Code:
...
Proccess proc = Runtime.getRuntime().exec("su");
OutputStream stream = proc.getOutputStream();
stream.write("busybox dd if=/sdcard/recovery.img of=/dev/block/mmcblk0p12".getBytes());
stream.flush();
...
Pretty simple isn't it, now suppose you don't know anything about bash codes, what will you do?
Let me answer this question:
1) Learn some bash.
2) Use Cmd library with java codes.
Here is the same implementaion with Cmd library:
Code:
...
JavaRoot root = JavaRoot.newInstance(getPackageName(), RootCommands.class.getName(), false);
root.execute("/sdcard/recovery.img", "/dev/block/mmcblk0p12")
...
And in RootCommands.java file (should not be an inner class):
Code:
package com.bassel.example;
import com.bassel.cmd.Command;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main extends Command
{
private byte[] buffer;
private File recovery, partition;
private FileInputStream in;
private FileOutputStream out;
//static main method implementation is a must
@Override
public static void main(String[] args)
{
//required to start
new Main().run(args);
}
//the begging just like onCreate
@Override
public void onRun()
{
if(argsCount() < 2) showUsage();
System.out.println(String.format("Flashing %s to %s", getArg(0), getArg(1)));
recovery = new File(nextArg());
partition = new File(nextArg());
buffer = new byte[1024 * 1024];
try
{
in = new FileInputStream(recovery);
out = new FileOutputStream(partition);
while(in.read(buffer) > 0)
{
out.write(buffer);
out.flush();
}
in.close();
out.close();
System.out.println("Flashed successfully!");
}
catch (Exception e)
{e.printStackTrace(System.err);}
}
//called upon calling showUsage()
@Override
public void onShowUsage()
{
System.err.println("Two args are needed!");
}
//called once an exception is caught
@Override
public void onExceptionCaught(Exception exception)
{
exception.printStackTrace(System.err);
}
}
Quite lengthy but sometimes we prefer using Java codes to bash ones, don't we?
Here is another example for listing /data files:
Code:
package com.bassel. example;
import java.io.File;
//Without extending Command.class
public class Main
{
@Override
public static void main(String[] args)
{
String[] files = new File("/data").list();
for(String file : files)
{
System.out.println(file);
}
}
}
Usage in depth:
Check root access:
Cmd.root();
No root:
Cmd.SH.ex(String command, String... args);
Cmd.SH.ex(String[] commands);
Cmd.SH.ex(List commands);
With root access:
Cmd.SU.ex(String command, String... args);
Cmd.SU.ex(String[] commands);
Cmd.SU.ex(List commands);
JavaRoot java = JavaRoot.newInstance(String packageName, String className, boolean isSystemApp);
java.execute(String... args);
java.executeInBackground(String... args);
All previous methods aside of the last one:
java.executeInBackground(String... args);
return an instance of type Output that has the following methods:
Code:
boolean success() //returns true if process exit value = 0 else false
String getString() //returns output in String format
String[] getArray() //returns output in String Array format
List getList() //returns output in String List format
int getExitValue() //returns process exit value
String toString() //returns process status and output in String format
Converting:
String string = ...;
String[] array = ...;
List list = ...;
String s1 = Convert.array2string(array);
String s2 = Convert.list2string(list);
String[] a1 = Convert.list2array(list);
String[] a2 = Convert.string2array(string);
List l1 = Convert.array2list(array);
List l2 = Convert.string2list(string);
Library GitHub link:
Cmd (licensed under Apache License, Version 2.0)
Examples:
Window Manipulator

Help me translate this coding

I'm learning how to manage data that I pull from DB (MYSQL) from this coding. I tried to figure out from free source coding but got stuck on this function, can anybody explain to me flow of this coding?
Code:
protected void onPostExecute(Void aVoid) {
name = names.split(":");
email = emails.split(":");
phone = phones.split(":");
combinedArray = combinedText.split(":");
listView.setAdapter(new ArrayAdapter<String>(RetrieveData.this,
android.R.layout.simple_list_item_1, combinedArray));
progressDialog.dismiss();
}
and when I tried to use this code, red line prompt out and saying that cannot resolved this constructor on if i change
Code:
listItems
to
Code:
names
variables on this
Code:
adapter=new ArrayAdapter<String>(this,
R.layout.list_item, R.id.txtitem, listItems);
I don't understand why I need to use 'split' to pull out the output on listview.

Categories

Resources