Friday, 19 December 2014

Android Programming Tips and Tricks

Showing Toast in Android

//Toast shown for  short period of time
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_SHORT).show();

//Toast shown for long period of time
Toast.makeText(getApplicationContext(), "Toast Message", Toast.LENGTH_LONG).show();
OR using custom layout for your toast

Toast myToast = new Toast(getApplicationContext());
myToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);

Getting all running Apps in Android

    private List<String> getRunningApps() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        PackageManager packageManager = getPackageManager();
        final List<RunningAppProcessInfo> runningProcesses = activityManager.getRunningAppProcesses();
        List<String> runningAppNames = new ArrayList<String>();
        for(RunningAppProcessInfo processInfo : runningProcesses) {
            CharSequence appName = null;
            try {
                appName = packageManager.getApplicationLabel(packageManager.getApplicationInfo(processInfo.processName, PackageManager.GET_META_DATA));
            } catch (NameNotFoundException e) {
                Log.e(TAG,"Application info not found for process : " + processInfo.processName,e);
        return runningAppNames;

Above code required permission -

  <uses-permission android:name="android.permission.GET_TASKS" />

Killing Background App

You can use  -

 ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

You can't kill the app in the foreground (your App) by this. You need to finish(). Also note this is for API 8 and above and needs permission KILL_BACKGROUND_PROCESSES.

Dynamically Creating Layout

LinearLayout linearLayout = new LinearLayout(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
linearLayout.addView(button, layoutParams);

Adding Scroll bar over a Layout

LinearLayout rootLinearLayout = new LinearLayout(this);
LinearLayout linearLayout = new LinearLayout(this);
LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ScrollView scrollView = new ScrollView(this);
scrollView.addView(linearLayout, layoutParams);
rootLinearLayout.addView(scrollView, layoutParams);

Closing current Activity


Note : You should put a return statement after that finish, because the method that called finish will be executed completely otherwise.

Getting Resources


Resources are under res directory. For example String resources are in res/string.xml  with content like - 

<?xml version="1.0" encoding="utf-8"?>

    <string name="app_name">Simple App Killer</string>
    <string name="about">About</string>


Getting View or Activity Content View


Note : R.layout.* are layouts you provide (in res/layout, for example).android.R.layout.* are layouts that ship with the Android SDK. Infact R.layout is actually shortcut for your.package.R.layout

Creating Menu

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);
        return true;

You need to override onCreateOptionsMenu method and use MenuInflater to inflate your menu. You also need to provide menu .Create a file name test_menu.xml under res/menu folder with content like -

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="" >
<item android:id="@+id/about"
          android:title="@string/about" />


To set onclick on the menu items you need to override onOptionsItemSelected method as follows -

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
                Toast.makeText(getApplicationContext(), "This App is created by Aniket Thakur", Toast.LENGTH_LONG).show();
                return true;
                return super.onOptionsItemSelected(item);

Getting Managers

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
PackageManager packageManager = getPackageManager();

Note : these manages will not be available before onCreate() method. Also recollect these managers form second layer of Android architecture after application layer. These managers talk to the kernel layer using native libraries and android runtime.

Hiding Action Bar App Icon and App Name


Note : This requires API level 11 or above.

Saving Persistent Data

When you application needs to save some persistent data you should always do it in onPause() methods. Because if android OS kills your process then onStop() and onDestroy() methods are never called.

Starting new Activity with startActivity() and startActivityForResult() methods

You can start a new activity by creating an intent object and then calling 
  • startActivity(Intent) [Simply starts new Activity]
  • startActivityForResult(Intent, int) [Start new Activity expecting some result from new activity to be sent to the activity from which new activity was started].
You can also send some extra information in the intent using Intent classes putExtra() method. Later you can reference the intent that started the new activity in the new activity as getIntent() and then retrieve the additional information as getStringExtra().

MyActivity :

Intent intent = new Intent(this, MyNewActivity.class);
intent.putExtra("musicEnabled", "yes");

MyNewActivity :

Intent intent = getIntent();
String musicEnabled = intent.getStringExtra("musicEnabled");
//more logic here   

If you use startActivityForResult(Intent, int) method [if you need to activity you are starting to return some data back to the activity that started it] then you need to call -

MyActivity  :

static private final int GET_TEXT_REQUEST_CODE = 1;
Intent intent = new Intent(this, NewActivity.class);

you can then retrieve the returned result in a callback method -

MyActivity  :

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("NewActivity", "Entered onActivityResult()");
        if(resultCode == Activity.RESULT_OK && requestCode == GET_TEXT_REQUEST_CODE){

and then in your NewActivity class you have to set the result with RESULT_OK code as follows -

MyNewActivity  :

        String input = myEditText.getText().toString();
        Intent intent  = new Intent();
        intent.putExtra("MY_VALUE",input );
        setResult(Activity.RESULT_OK, intent);

Showing Notifications

Code is as follows - 

Intent browseIntent = new Intent(Intent.ACTION_VIEW, Uri
PendingIntent pendingIntent = PendingIntent.getActivity(
        MainActivity.this, 0, browseIntent,
Notification.Builder notificationBuilder = null;
notificationBuilder = new Notification.Builder(
        .setContentTitle("Notification Title")
        .setContentText("Notification Content Text")
        .setTicker("Ticker Text");

NotificationManager notificationManager = (NotificationManager) MainActivity.this

Ticker Text will be seen as -

and you can see the actual notification on pulling down the notification bar

You can also set your own layout as view for the notification. For that you can do -

RemoteViews mContentView = new RemoteViews(MainActivity.this

        .getPackageName(), R.layout.activity_main);

notificationBuilder = new Notification.Builder(


Note: PendingIntent is a special type of intent that allows 3rd party code (in this case Notification Manager) to execute application code with the same permission as the application. When you click on above notification browser should open and display

More to Come....
PS : This list will keep updating. If you want me to add something in above list please provide it in the comments.

Good Read

No comments:

Post a Comment

t> UA-39527780-1 back to top