Android Tutorials

Google+

Wednesday 16 October 2013

Basic Android background Service

Running sample program for background service

Step 1 :
Create sample service class
package com.bishnu.sample.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
 
   String tag="TestService";
   @Override
   public void onCreate() {
       super.onCreate();
       Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();      
       Log.i(tag, "Service created...");
   }
 
   @Override
   public void onStart(Intent intent, int startId) {      
       super.onStart(intent, startId);  
       Log.i(tag, "Service started...");
   }
   @Override
   public void onDestroy() {
       super.onDestroy();
       Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
   }

   @Override
   public IBinder onBind(Intent intent) {
       return null;
   }
}
Step 2 :
Create sample Activity class
package com.javaorigin.android.sample.service;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class SampleAction extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {      
       super.onCreate(savedInstanceState);
       TextView view = new TextView(this);      
       view.setText("Service Test");
       Intent i = new Intent();
       i.setClassName( "com.javaorigin.android.sample.service",
        "com.javaorigin.android.sample.service.MyService" );
       bindService( i, null, Context.BIND_AUTO_CREATE);
       this.startService(i);      
       setContentView(view);
   }
}


Step 3:
Configure AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.javaorigin.android.sample.service" android:versionCode="1"
   android:versionName="1.0">
   <application icon="@drawable/icon" label="@string/app_name">
       <service class=".MyService" name=".MyService">
         <intent-filter>
           <action android:value="com.javaorigin.android.sample.service.MY_SERVICE"
                   android:name=".MyService" />

           </intent-filter>
       </service>
      <activity android:name=".SampleAction"
                 android:label="@string/app_name">
           <intent-filter>
               <action name="android.intent.action.MAIN">
               <category name="android.intent.category.LAUNCHER">
           </intent-filter>
       </activity>

   </application>
   <uses-sdk minsdkversion="8">

</manifest>


Integrate Google Analytic into your Android Application

Google Analytics data about your Android app will help you see if your design is logical and may lead you to think of ways to increase user engagement. 
Google Analytics is a great tool for tracking metrics about how users are interacting with your applications or websites. It is so simple to set up that I highly recommend you use it in your Android development. In this tutorial, I describe how to set up and use Google Analytics for Android and share insights into the information I've gleaned from it.

Google Analytics setup

First, you must sign up to use Google Analytics through an existing Google account. Next, you must create an account for your application. It doesn't matter what URL you use -- just enter something meaningful that you'll be able to remember later when you look up statistics.

Android setup

In order to set up Google Analytics inside your Android application, download the zip file for Android. Extract the file once it downloads and copy the jar file inside into the lib folder of your Android project. (If a lib folder does not already exist, simply create one.) Then, if you're using Eclipse, follow these steps:
  1. Right-click on your project.
  2. Choose Properties.
  3. Choose Java Build Path from the menu on the left.
  4. Click the Libraries tab at the top of the right side.
  5. Click Add JARs....
  6. Choose the jar file inside the lib folder.
  7. Click the OK button.
Next, add the following permissions to your application's Manifest.xml file:
  • <uses-permission android:name="android.permission.INTERNET" />
  • <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Now that your project is set up to start using the Google Analytics API, you should insert the necessary code and start testing. To keep things simple, let's focus on two main aspects of tracking: page views and events. You can get more advanced by tracking custom variables, Ecommerce data, setting sampling rates, and even tracking installation referrals, but I'll leave you to investigate all those options once are you comfortable with the basics.

Page views

It makes sense to track each Activity of your application as a page, so below is a sample onCreate method showing you how to track a page view:
private GoogleAnalyticsTracker mGATracker;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGATracker = GoogleAnalyticsTracker.getInstance();
mGATracker.startNewSession( "UA-YOUR-ACCOUNT-HERE", this );
mGATracker.trackPageView( "/YourActivity" )'
}
catch( Exception error ) {
Log.e( "<YOUR_TAG>", "onCreate: " + error.toString() );
}
}
Alternatively, you could have specified a dispatch interval for startNewSession as such, where 20 is the number of seconds between automatic dispatches of data:
mGATracker.startNewSession( "UA-YOUR-ACCOUNT-HERE", 20, this );
By tracking each activity as a page view, you can see how deep users are navigating through your application, as well as which sections are the most and the least popular.

Events

Events are the next thing you'll want to track. If you're having trouble deciding which events to track, start with all of your buttons' onClick listeners. Below is a sample listener:
public void ButtonClick( View v ) {
try {
// Category, Action, Label, Value
mGATracker.trackEvent( "Clicks", "Button", "clicked", 0 );
}
catch( Exception error ) {
Log.e("<YOUR_TAG>", "ButtonClick: " + error.toString() );
}
By tracking and analyzing user clicks in your application, you'll be able to figure out which options in your application are most popular, which UI elements might be difficult for users to identify as a clickable area, and overall user engagement.
I also highly suggest you track an event every time the user long-presses an item and/or uses the hardware menu key. I find the two UI elements associated with these actions (context menus and the options menu) in Android incredibly useful when trying to design a UI because it allows the interface to be much cleaner and simpler, while also still providing many actionable choices. I've learned through experience and analytics that the average user hardly ever thinks to long-press items or hit the menu button. As a power user, these are the first two things I try when I'm not sure what to do next inside an app, so this information has made me re-think which elements I stick in the options menu and has also forced me to stop using long-press context menus.

Dispatching

When you call startNewSession on your GoogleAnalyticsTracker object, you may pass in a dispatch interval parameter that will automatically dispatch (send) the collected data to Google's servers. However, Google suggests that you batch your dispatch requests to reduce the amount of overall network traffic, which will also cut down on battery usage, so I prefer to call dispatch manually in the onDestroy method of my activities. This is also a good place to callstopSession on your GoogleAnalytics object.
@Override
public void onDestroy() {
try {
super.onDestroy();
mGATracker.dispatch();
mGATracker.stopSession();
}
catch( Exception error ) {
Log.e("<YOUR_TAG>", "onDestroy: " + error.toString() );
}
}

Conclusion

The benefits you'll reap from using Google Analytics in your Android applications are well worth the little bit of effort it takes to integrate. All the information gathered can help you figure out if you've designed and organized your app in a logical manner and may help you think of ways to increase user engagement, all of which will go a long way towards making you a better developer.

Friday 11 October 2013

Android ImageButton Selector

In last Android tutorial, you use “ImageButton” to display a “Button” with a customized background image easily. However, you can do more than that just a simple image, Android allow you to change the button’s image depends on different states like button is focused or button is pressed.
This example is referenced from this Android custom button article, with minor changes.
1. Add Images to Resources
Prepare 3 images for button states, and put it into “resource/drawable” folder.
  1. button_normal_green.png – Default image button.
  2. button_focused_orange.png – Display when button is focused, for example, when phone’s keypad is move (focus) on this button.
  3. button_pressed_yellow.png – Display when button is pressed.

2. Add Selector for different button states

Now, create a new XML file in “res/drawable/” folder, in whatever name you want, in this case, we just give a name as “new_button.xml“. This file defined which button state is belong to which image.
Now, you can refer to this button via this Id : @drawable/new_button.
File : res/drawable/new_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed_yellow"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused_orange"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_normal_green" />
</selector>

3. Add Button

Open “res/layout/main.xml” file, add a normal button, and attach the background image to above “new_button” via “android:background="@drawable/new_button
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/new_button" />
 
</LinearLayout>

4. Code Code

A normal button with a simple click listener.
File : MyAndroidAppActivity.java
package com.bishnu.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
 
public class MyAndroidAppActivity extends Activity {
 
 Button imageButton;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  addListenerOnButton();
 
 }
 
 public void addListenerOnButton() {
 
  imageButton = (Button) findViewById(R.id.imageButtonSelector);
 
  imageButton.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View arg0) {
 
    Toast.makeText(MyAndroidAppActivity.this,
     "ImageButton (selector) is clicked!",
     Toast.LENGTH_SHORT).show();
 
   }
 
  });
 }
}

Android Image Button

In Android, you can use “android.widget.ImageButton” to display a normal “Button“, with a customized background image.
In this tutorial, we show you how to display a button with a background image named “android_button.png“, when user click on it, display a short message. As simple as that.
Note
You may also like this Android ImageButton selector example, which allow to change button’s images depends on button states.

1. Add Image to Resources

Put image “android_button.png” into “res/drawable-?dpi” folder. So that Android know where to find your image.

2. Add ImageButton

Open “res/layout/main.xml” file, add a “ImageButton” tag, and defined the background image via “android:src“.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android_button" />
 
</LinearLayout>

3. Code Code

Here’s the code, add a click listener on image button.
File : MyAndroidAppActivity.java
package com.bishnu.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
 
public class MyAndroidAppActivity extends Activity {
 
 ImageButton imageButton;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  addListenerOnButton();
 
 }
 
 public void addListenerOnButton() {
 
  imageButton = (ImageButton) findViewById(R.id.imageButton1);
 
  imageButton.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View arg0) {
 
      Toast.makeText(MyAndroidAppActivity.this,
    "ImageButton is clicked!", Toast.LENGTH_SHORT).show();
 
   }
 
  });
 
 }
 
}

Android Toast

An Android, Toast is a notification message that pop up, display a certain amount of time, and automtaically fades in and out, most people just use it for debugging purpose.
Code snippets to create a Toast message :
//display in short period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
 
//display in long period of time
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
In this tutorial, we will show you two Toast examples :
  1. Normal Toast view.
  2. Custom Toast view.

1. Normal Toast View

Simple Toast example.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Toast" />
 
</LinearLayout>
File : MainActivity.java
package com.bishnu.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
 private Button button;
 
 public void onCreate(Bundle savedInstanceState) {
 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  button = (Button) findViewById(R.id.buttonToast);
 
  button.setOnClickListener(new OnClickListener() {
 
     @Override
     public void onClick(View arg0) {
 
        Toast.makeText(getApplicationContext(), 
                               "Button is clicked", Toast.LENGTH_LONG).show();
 
     }
  });
 }
}

Android Custom Dialog

n this tutorial, we show you how to create a custom dialog in Android. See following steps :
  1. Create a custom dialog layout (XML file).
  2. Attach the layout to Dialog.
  3. Display the Dialog.
  4. Done.
Note
You may also interest to read this custom AlertDialog example.

1 Android Layout Files

Two XML files, one for main screen, one for custom dialog.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonShowCustomDialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Custom Dialog" />
 
</LinearLayout>
File : res/layout/custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp" />
 
    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF" 
        android:layout_toRightOf="@+id/image"/>/>
 
     <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text=" Ok "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/image"
        />
 
</RelativeLayout>

2. Activity

Read the comment and demo in next step, it should be self-explorary.
File : MainActivity.java
package com.bishnu.android;
 
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
 final Context context = this;
 private Button button;
 
 public void onCreate(Bundle savedInstanceState) {
 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  button = (Button) findViewById(R.id.buttonShowCustomDialog);
 
  // add button listener
  button.setOnClickListener(new OnClickListener() {
 
    @Override
    public void onClick(View arg0) {
 
   // custom dialog
   final Dialog dialog = new Dialog(context);
   dialog.setContentView(R.layout.custom);
   dialog.setTitle("Title...");
 
   // set the custom dialog components - text, image and button
   TextView text = (TextView) dialog.findViewById(R.id.text);
   text.setText("Android custom dialog example!");
   ImageView image = (ImageView) dialog.findViewById(R.id.image);
   image.setImageResource(R.drawable.ic_launcher);
 
   Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
   // if button is clicked, close the custom dialog
   dialogButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
     dialog.dismiss();
    }
   });
 
   dialog.show();
    }
  }); }
}

Android Prompt User Input Dialog

In this tutorial, we will enchance the previous AlertDialog example, to make it able to accept user input, just like aPromptDialog. More specific, this is a custom AlertDialog example.
See following steps :
  1. Create a prompt dialog layout (XML file).
  2. Attach the prompt dialog layout to AlertDialog.Builder.
  3. Attach the AlertDialog.Builder to AlertDialog.
  4. Done.
Note
You may interest to read this custom dialog example.

1 Android Layout Files

Two XML files, one for main screen, one for prompt dialog.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonPrompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Prompt Dialog" />
 
    <EditText
        android:id="@+id/editTextResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
    </EditText>
 
</LinearLayout>
File : res/layout/prompts.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Type Your Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <requestFocus />
 
    </EditText>
 
</LinearLayout>

2. Activity

Read the comment and demo in next step, it should be self-explorary.
File : MainActivity.java
package com.bishnu.android;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends Activity {
 
 final Context context = this;
 private Button button;
 private EditText result;
 
 public void onCreate(Bundle savedInstanceState) {
 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 
  // components from main.xml
  button = (Button) findViewById(R.id.buttonPrompt);
  result = (EditText) findViewById(R.id.editTextResult);
 
  // add button listener
  button.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View arg0) {
 
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(context);
    View promptsView = li.inflate(R.layout.prompts, null);
 
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
      context);
 
    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);
 
    final EditText userInput = (EditText) promptsView
      .findViewById(R.id.editTextDialogUserInput);
 
    // set dialog message
    alertDialogBuilder
     .setCancelable(false)
     .setPositiveButton("OK",
       new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,int id) {
      // get user input and set it to result
      // edit text
      result.setText(userInput.getText());
         }
       })
     .setNegativeButton("Cancel",
       new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog,int id) {
      dialog.cancel();
         }
       });
 
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
 
    // show it
    alertDialog.show();
 
   }
  });
 }
}