List all installed packages on Android

To see a list of all the installed packages on your Android device.
You need to cd into the folder where the Android adb.exe file is. On windows it is usually in:

C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools.

Then type in:

adb shell pm list packages

GitHub commands

To clone a repository to a specific folder. Using Bash, cd into the folder you want the repo to be cloned into. Then on the GitHub webpage where your repo is, click the clone button, this will present you with a http address. Copy this and add it to the command:

git clone

Then make sure you cd into the newly cloned folder.
If you make any changes to code and want to commit them. Type in:

git status

This will show you the ‘branch’ you are on and if there are any changes that can be committed. If there are any files that have been created or modified then they will be displayed with a red font.
To add these files you type in:

git add

or if you have a lot of files to add and want to do it in one go, type in:

git add .

Next you have to ‘commit’ these files. To do that type in:

git commit -m 'type a descriptive message here about this commit'

If you haven’t given your email and name then at this point you will be asked to do so. The command are:

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

If you were asked to give your email and name then after you do you will need to type in the git commit -m ‘message’ command again.

You can now type in the command:

git log

to see a list of your commits.

To push the commits to your GitHub repository type in:

git push origin master

If you haven’t logged into your account you will be asked to do so. Just type in your username and GitHub password and the files will then be pushed to GitHub.

Use Android shared preferences.

Shared preferences stores data as key/value pairs.

To put the key/value pair into shared preferences you can use the .commit() or .apply() command.

apply()

This saves your data into memory immediately and saves the data to disk on a separate thread. So there is no chance of blocking the main thread (your app won’t hang).

It is the preferred technique but has only been available since Gingerbread (API 9, Android 2.3).

commit()

Calling this will save the data to the file however, the process is carried out in the thread that called it, stopping everything else until the save is complete. It returns true on successful completion, false on failure.

Use commit() if you need confirmation of the success of saving your data or if you are developing for pre-Gingerbread devices. commit() has been available since API 1

The following code will setup shared_prefs file and store different values.

public static final String MyPREFERENCES = "MyPrefs"; //This will be the name of the shared preferences file
public static final String Name = "nameKey";


SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, "string");
editor.putBoolean(Name2, false);
editor.putInt(Name3, 23424);
editor.apply();

 

 

A good idea is to put the code for shared preferences into its own class and declare static methods. Here is an example for putting a boolean value into shared preferences:

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class PreferencesMgr {

    private static SharedPreferences sSharedPreferences;
    public static final String MyPREFERENCES = "MyPrefs";//This will be the name of shared preferences file.

    public static void setBoolean(Context context, String key, boolean data ){
        Log.i("PrefMgr setBoolean", "key: " + key + ", data: " + data);
        sSharedPreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sSharedPreferences.edit();
        editor.putBoolean(key, data);
        editor.apply();
    }

    public static Boolean getBoolean(Context context, String key){
        sSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sSharedPreferences.getBoolean(key, false);

    }
}

You then set the boolean value with:

PreferencesMgr.setBoolean(this,KEY,true);

and you retrieve it using:

boolean myBoolean = PreferencesMgr.getBoolean(context, KEY);

You can view the shared_prefs file using a command prompt after the file has been created.

 

 

View Android shared preferences file with command prompt

To view the shared_prefs file for an android app first open up your command prompt and change directory (cd command)to the directory that has your adb.exe file in it. On windows it is usually in:
C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools.
If you have installed the Android SDK to a different drive use the 'cd /d' command to change drives

Then type in the following commands:

adb shell

run-as com.your.package

ls //list the files in this directory

cd shared_prefs

ls

cat MyPrefs.xml

Simulate BOOT_COMPLETED on android emulator

If you are test an android app that launches an app or service on startup you will be using the BOOT_COMPLETED broadcast to trigger your app or service. Testing this kind of thing is usually done with an emulator as turning off and on a physical phone takes too long. With an android emulator (either the native emulator or GenyMotions) the quickest way is too launch a command prompt, change directory into the directory that holds the adb.exe file. This will be in the Android folder and on windows its normally located on the C drive. The type in the command:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED

This will restart the emulator quicker than any other method I have found.

Java Handler

A Handler is an Android class you can use to schedule code that should be run at some point in the future.  You can also use it to post code that needs to run on a different thread.

To use the Handler, you wrap the code you wish to schedule in a Runnable object, and then use the Handler post() and postDelayed() methods to specify when you want the code to run.

post()
The post() method posts code that needs to be run as soon as possible (which is usually almost immediately). The post() method takes one parameter, an object of type ‘Runnable’. A ‘runnable’ is simply a job you want to run, just like in Java. You put the code you want to run in the Runnable’s run() method, and the Handler will make sure the code is run as soon as possible. E.g:

final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
//code to be executed is put here
}

postDelayed()
The postDelayed() method works in a similar way to the post() method except that you use it post code that should be run in the future. The postDelayed() method takes two parameters: a Runnable and a long. The Runnable contains the code you want to run in its run() method, and the long specifies the number of milliseconds you wish to delay the code by. The code will run as soon as possible after the delay. E.g:

handler.postDelayed(Runnable, long);//long is milliseconds delay before code is executed

 

Android AsyncTask

This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

To use AsyncTask you extend your class with: AsyncTask<ParamsProgressResult>.

Where:

Params is an array of inputs sent in when the AsyncTask is called.

Progress is the progress of the AsyncTask. This is used if you are displaying a progress bar.

Result is the type of result the AsyncTask will return.

 

The AsyncTask has four subclasses:

onPreExecute: action to be done before the main task.

doInBackground: the main task that is to be performed. This method signature looks like:

protected Result doInBackGround(Params...params){}

Within the doInBackground method you may want to access the individual arguments sent in. As ‘params’ is an array of arguments, you can access the individual arguments sent in with: params[index]. If only one argument is sent in then it will be: params[0]

This method always returns something.

onProgressUpdate: used for the progress display.

onPostExecute: action to be performed after the main task has been completed. Often this method uses the returned data from the doInBackground method. This method signature is:

protected void onPostExecute(Result name){}

 

If you have a class:

private class myClass extends AsyncTask<String, void, String>{}

To execute the Async task on a this class:

myClass().execute(arg1, arg2,...);

Serializable

Serialization is simply turning an existing object instance into a byte array. After a serialized object has been written into a file, it can be read from the file and deserialized. This the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

public final void writeObject(Object x) throws IOException
This method serializes an Object and sends it to the output stream.

public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

Employee class

public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;

public void mailCheck()
{
System.out.println("Mailing a check to " + name + " " + address);
}
}

Serialize Class

import java.io.*;

public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;

try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
}//SerializeDemo

DeserializeDemo Class

import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}//DeserializeDemo

Read data stream into StringBuilder (Java)

To read a data stream into a string builder use the following code:


StringBuffer readInput(String sInputSream){
String url = "https://website.com";
URL obj = null;
 try {
 obj = new URL(url);
 } catch (MalformedURLException e) {
 e.printStackTrace();
 }
HttpURLConnection con = null;
 try {
 con = (HttpURLConnection) obj.openConnection();
 } catch (IOException e) {
 e.printStackTrace();
 }
BufferedReader in = null;
 try {
 in = new BufferedReader(
  new InputStreamReader(con.getInputStream()));
 } catch (IOException e) {
 e.printStackTrace();
 }
String inputLine;
StringBuffer response = new StringBuffer();

 try {
 while ((inputLine = in.readLine()) != null) {
 response.append(inputLine);
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 try {
 in.close();
 } catch (IOException e) {
 e.printStackTrace();
 }

//print result
System.out.println(response.toString());
return response;
}

(This code uses ‘BufferedReader‘ which reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
In this example we use a buffer size of 8.

The ‘InputStreamReader‘ is also used. This method is a bridge from byte streams to character streams.
It reads bytes and decodes them into characters using a specified charset. In this case we use the iso-8859-1
charset.)

Reading data stream into a StringBuilder (Android)

To read a data stream into a string builder use the following code:


BufferedReader reader = new BufferedReader(new InputStreamReader(sInputStream, "iso-8859-1"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}sInputStream.close();
sRawString = stringBuilder.toString();

(This code uses ‘BufferedReader‘ which reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
In this example we use a buffer size of 8.

The ‘InputStreamReader‘ is also used. This method is a bridge from byte streams to character streams.
It reads bytes and decodes them into characters using a specified charset. In this case we use the iso-8859-1
charset.)