Learn Python


Click to Learn Python3

Tuesday, March 29, 2011

ListActivity with checkbox using AsyncTask with sleep time example in android

We are going to see about using the ListActivity with checkbox example and we are going to see, how to using the AsyncTask with a good example, here we will be using sleep call, it is optional. The view will be like this



First we can see about using sleep option in android, in our code we used this


Java

for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}


Here SystemClock.sleep(200); is used to sleep for a while, for this ListActivity with checkBox or AsyncTask this is not compulsory, this is used in this example for making to know about this sleep option.

The ListActivity with check box can be done by using this xml code in the layout


XML

<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>


like that we need to insert the code in the java file as


Java

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_checked, new ArrayList()));


and for check operation we need to override the function as


Java

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}


That will do for showing a List view using the ListActivity, for using the AsyncTask, we need to call the AsyncTask class like


Java

new AddStringTask().execute();


On this call the AsyncTask class will be called


Java

class AddStringTask extends AsyncTask {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}

return (null);
}

@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter) getListAdapter()).add(item[0]);
}

@Override
protected void onPostExecute(Void unused) {
setSelection(3);
Toast.makeText(AsyncTaskDemo.this, "Done!", Toast.LENGTH_SHORT).show();
}
}


The full AsyncTaskDemo.java file will be like this


Java

package com.async.demo;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

/**
*
* @author http://www.android-codes-examples.blogspot.com/
*
*/

public class AsyncTaskDemo extends ListActivity {
private static String[] items = { "Joseph", "George", "Mary", "Antony", "Albert",
"Michel", "John", "Abraham", "Mark", "Savior", "Kristopher",
"Thomas", "Williams", "Assisi", "Sebastian", "Aloysius", "Alex", "Daniel",
"Anto", "Alexandar", "Brito", "Robert", "Jose",
"Paul", "Peter" };

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_checked, new ArrayList()));

new AddStringTask().execute();
}

class AddStringTask extends AsyncTask {
@Override
protected Void doInBackground(Void... unused) {
for (String item : items) {
publishProgress(item);
SystemClock.sleep(200);
}

return (null);
}

@Override
protected void onProgressUpdate(String... item) {
((ArrayAdapter) getListAdapter()).add(item[0]);
}

@Override
protected void onPostExecute(Void unused) {
setSelection(3);
Toast.makeText(AsyncTaskDemo.this, "Done!", Toast.LENGTH_SHORT).show();
}
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
CheckedTextView check = (CheckedTextView)v;
check.setChecked(!check.isChecked());
}


}


You can download the full source code


Download source


Have a good day.

Example code for OnKeyDown listener in Android

In this example Toast is shown for the key presses.



The approach is simple, just we need to put this code, thats all


Java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch(keyCode)
{
case KeyEvent.KEYCODE_CAMERA:
Toast.makeText(KeyActions.this, "Pressed Camera Button", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_1:
Toast.makeText(KeyActions.this, "Pressed 1", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_HOME:
Toast.makeText(KeyActions.this, "Pressed Home Button", Toast.LENGTH_SHORT).show();
return true;

case KeyEvent.KEYCODE_BACK:
Toast.makeText(KeyActions.this, "Pressed Back Button", Toast.LENGTH_SHORT).show();
Intent result = new Intent("Complete");
setResult(Activity.RESULT_OK, result);
finish();
return true;
}

return false;
}


For every key there is the code, after entering the KeyEvent. the eclipse will show the list of codes available.

If you have doubts means

The full source code

Download source


Have a good day.

Wednesday, March 23, 2011

Customized ListView item's selection color can be changed on touching or selecting the item in the list

On selection, on focus, on touch of the items we can change the color of the item, by default android will show a color, we can change it as we like. For that we need this xml to be stored inside the color folder, here only we need mention the colors for each listeners




list_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/grey" />
<item android:state_pressed="true"
android:drawable="@color/blue" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/blue" />
</selector>



That list_bg.xml will be called in the customized list xml as background


list.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="wrap_content"
android:layout_margin="2dp" android:background="@color/list_bg">

<TextView android:id="@+id/post" android:gravity="center_vertical"
android:layout_width="wrap_content" android:layout_height="50dp"
android:textSize="20sp" android:textColor="#D0640D"
android:layout_toRightOf="@+id/bite_image" />

</RelativeLayout>


This one is the main xml for the Lister.java


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">

<ListView android:id="@android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:smoothScrollbar="true"
android:background="#fff" android:cacheColorHint="#fff"
android:fastScrollEnabled="false" android:clickable="true"
android:layout_marginBottom="36dp" />

</LinearLayout>



The Lister.java will be like this, the main thing is the list_bg.xml only


Lister.java

package com.list.viewer;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Lister extends ListActivity{

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] captionArray = { "USA","India","England","Russia","Europe","Canada","Srilanka","Singapore","Thailand","Australia"};
ItemsAdapter ItemsAdapter = new ItemsAdapter(
Lister.this, R.layout.list,
captionArray);
setListAdapter(ItemsAdapter);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
// super(context, textViewResourceId, items);
this.items = items;
}

// @Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list, null);
}
TextView post = (TextView) v
.findViewById(R.id.post);
post.setText(items[position]);

return v;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}
}
}





The full source code

Download source


Have a good day.

Monday, March 21, 2011

Multiple ListView and custom listview example with click listener functions

Multiple listview can be placed inside a Activity. Here i am having two listviews



As shown in the above image, the left side displaying list view is customized listview, it that listview we will be showing a imageview and a textview, On clicking the item of that listview, the second listview will be generated.

The xml layout for that page will be like this


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:gravity="center"
android:layout_height="fill_parent" android:background="#cccccc">
<TextView android:layout_width="fill_parent" android:textColor="#000"
android:layout_height="wrap_content" android:text="Multiple ListView Example" />
<LinearLayout android:orientation="horizontal" android:layout_marginTop="10dp" android:gravity="center_horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<ListView android:id="@+id/ListView1" android:layout_width="130dp"
android:background="#fff" android:cacheColorHint="#fff"
android:layout_height="wrap_content" />
<TextView android:text="==>" android:layout_height="wrap_content" android:textColor="#000"
android:layout_width="wrap_content"></TextView>
<ListView android:id="@+id/ListView2" android:layout_width="130dp"
android:background="#4c6f7e" android:cacheColorHint="#4c6f7e"
android:layout_height="wrap_content" />
</LinearLayout>

</LinearLayout>


For the customized listview the coding will be like this, it will show the customized listview with a imageview and textview for each item


Java

private String[] list1 = {"Icon", "Icon Creator", "Image", "Image Creator"};
private ListView lister1;
lister1=(ListView)findViewById(R.id.ListView1);
ItemsAdapter itemsAdapter = new ItemsAdapter(
ListViewExample.this, R.layout.list,
list1);
lister1.setAdapter(itemsAdapter);


In the above example we need to explicitly use a layout, the layout will be


list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="100dp"
android:layout_height="fill_parent"
>
<ImageView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:src="@drawable/icon" android:id="@+id/image"/>
<TextView android:textColor="#000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" android:id="@+id/desc"
/>
</LinearLayout>



For the second listview, is normal listview, which is used with the pre defined layout android.R.layout.simple_list_item_1

The full ListViewExample.java file will be like this


ListViewExample.java

package com.list.viewer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/** http://www.android-codes-examples.blogspot.com/ */
public class ListViewExample extends Activity {

private String[] list1 = { "Icon", "Icon Creator", "Image", "Image Creator" };
private String[] list21 = { "Design", "Creation", "Selection", "Caller" };
private String[] list22 = { "Investor", "Producer", "Controller",
"Publisher" };
private String[] list23 = { "Designer", "Maker", "Creator", "Asignment" };
private String[] list24 = { "Arranger", "Caller", "Solution", "Result" };

private ListView lister1;
private ListView lister2;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lister1 = (ListView) findViewById(R.id.ListView1);
lister2 = (ListView) findViewById(R.id.ListView2);
ItemsAdapter itemsAdapter = new ItemsAdapter(ListViewExample.this,
R.layout.list, list1);
lister1.setAdapter(itemsAdapter);
lister2.setAdapter(new ArrayAdapter(ListViewExample.this,
android.R.layout.simple_list_item_1, list21));
lister1.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView arg0, View arg1,
int positon, long arg3) {
String[] lister = null;
switch (positon) {
case 0:
lister = list21;
break;
case 1:
lister = list22;
break;
case 2:
lister = list23;
break;
case 3:
lister = list24;
break;
default:
lister = list21;
}
lister2.setAdapter(new ArrayAdapter(
ListViewExample.this,
android.R.layout.simple_list_item_1, lister));
}
});
}

private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
TextView mDescription;
View view = convertView;
ImageView image;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.list, null);
}
image = (ImageView) view.findViewById(R.id.image);
mDescription = (TextView) view.findViewById(R.id.desc);
mDescription.setText(items[position]);
image.setBackgroundResource(R.id.image);
return view;
}

public int getCount() {
return items.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}
}
}




The full source code

Download source


Have a good day.

Wednesday, March 16, 2011

How to display Custom Dialog and designing a page without xml layout is given with example?

Custom Dialog appears like this



First we can see how we are going to display a button without using the xml layout,


Java

Button show = new Button(this);
show.setText("Click to view a Custom Dialog");
/** Setting FILL_PARENT for the width and height of the button */
show.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
/** Without the layout xml we are going to add the button to the screen */
setContentView(show);


Instead of using the xml layout in setContentView() we are using the new created Button's variable, likewise if we are using the linearlayout's variable means, we can display the component without using the layout xml.

In this example we used the layout params


Java

show.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));


Actually this is used for setting the layout width and height for the button.

Now we can come to showing Custom Dialog, for that we need to create a class which exetends Dialog, the class will be like this


CustomizeDialog.java

package com.custom.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CustomizeDialog extends Dialog implements OnClickListener {
Button close;

public CustomizeDialog(Context context) {
super(context);
/** It will hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);

close = (Button) findViewById(R.id.close);
close.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (v == close)
dismiss();
}

}


Then in the main class CustomDialog.java we need to call the CustomizeDialog.java class to show the custom dialog, like this


Java

CustomizeDialog customizeDialog = new CustomizeDialog(CustomDialog.this);
customizeDialog.show();


The full code of the CustomDialog.java will be like this


CustomDialog.java

package com.custom.dialog;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Gallery;
import android.view.WindowManager.LayoutParams;

public class CustomDialog extends Activity {
/** Called when the activity is first created. */
private Button show;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

show = new Button(this);
show.setText("Click to view a Custom Dialog");
/** Setting FILL_PARENT for the width and height of the button */
show.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
/** Without the layout xml we are going to add the button to the screen */
setContentView(show);
show.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
CustomizeDialog customizeDialog = new CustomizeDialog(CustomDialog.this);
customizeDialog.show();
}
});


}
}




The full source code

Download source


For AlertDialog you can see this blog http://android-codes-examples.blogspot.com/2011/03/how-to-display-alertdialog-and.html


Have a good day.

Tuesday, March 15, 2011

How to display AlertDialog and selection in Alert Dialog and selection with radio buttons with example?

We are going to see the Alert Dialog in detail.

First we going to see how to use a normal AlertDialog

The below code is enough to call AlertDialog,


Java
AlertDialog.Builder alert = new AlertDialog.Builder(ShowDialog.this);

alert.setTitle("This is Alert Dialog");
alert.setMessage("Sample alert dialog from http://www.android-codes-examples.blogspot.com");
alert.setIcon(R.drawable.icon);
alert.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
  }
 });
alert.setNegativeButton("No",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
  }
 });

alert.show();


Next we are going to see how to call a AlertDialog with ListView for selection purpose


Java
final CharSequence[] items = {"India", "US", "UK", "Australia"};

AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
builder.setTitle("Alert Dialog with ListView");
builder.setIcon(R.drawable.icon);
builder.setItems(items, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
 Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});
AlertDialog alert = builder.create();

alert.show();


Next we are going to see how to call a AlertDialog with ListView with Radio button for selection purpose


Java
final CharSequence[] items = {"India", "US", "UK", "Australia"};

AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
builder.setTitle("Alert Dialog with ListView and Radio button");
builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {
 Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
    }
});

builder.setPositiveButton("Yes",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
  }
 });
builder.setNegativeButton("No",
 new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int id) {
   Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
  }
 });
AlertDialog alert = builder.create();
alert.show();


A sample with all the three examples of alertdialog is follows:


ShowDialog.java
package com.display.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ShowDialog extends Activity {
/** http://www.android-codes-examples.blogspot.com/ */
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 Button alert = (Button) findViewById(R.id.alert);
 Button customList = (Button) findViewById(R.id.customList);
 Button customListRadio = (Button) findViewById(R.id.customListRadio);
 
 alert.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  AlertDialog.Builder alert = new AlertDialog.Builder(ShowDialog.this);

  alert.setTitle("This is Alert Dialog");
  alert
    .setMessage("Sample alert dialog from http://www.android-codes-examples.blogspot.com");
  alert.setIcon(R.drawable.icon);
  alert.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int id) {
      Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
     }
    });
  alert.setNegativeButton("No",
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int id) {
      Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
     }
    });

  alert.show();
 }
 });
 
 customList.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  final CharSequence[] items = {"India", "US", "UK", "Australia"};

  AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
  builder.setTitle("Alert Dialog with ListView");
  builder.setIcon(R.drawable.icon);
  builder.setItems(items, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int item) {
   Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
      }
  });
  AlertDialog alert = builder.create();

  alert.show();
 }
 });
 
 customListRadio.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  final CharSequence[] items = {"India", "US", "UK", "Australia"};

  AlertDialog.Builder builder = new AlertDialog.Builder(ShowDialog.this);
  builder.setTitle("Alert Dialog with ListView and Radio button");
  builder.setIcon(R.drawable.icon);
  builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int item) {
   Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
      }
  });
  
  builder.setPositiveButton("Yes",
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int id) {
      Toast.makeText(ShowDialog.this, "Success", Toast.LENGTH_SHORT).show();
     }
    });
  builder.setNegativeButton("No",
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int id) {
      Toast.makeText(ShowDialog.this, "Fail", Toast.LENGTH_SHORT).show();
     }
    });
  AlertDialog alert = builder.create();
  alert.show();
 }
 });
}
}


Likewise for multiple choice in the alertdialog we need to use this line


Java
new DialogInterface.OnMultiChoiceClickListener() {
    public void onClick(DialogInterface dialog, int whichButton,
     boolean isChecked) {
          /** ... */
    }
});




The full source code

Download source


The different types of AlertDialog images will be like this





For Custom Dialog you can see this blog http://android-codes-examples.blogspot.com/2011/03/how-to-display-custom-dialog-and.html

Have a good day.

Monday, March 14, 2011

Make a phone call using Android code in application?

We can write code to make a call from the android application that we created.

The below code is enough to make a call from the application,


Java

Intent sIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:919894643826"));
startActivity(sIntent);


We can put this code in a click event, so that on clicking a button or textview the call be done.

Likewise we need to add this line inside the Manifest.xml file


XML

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


The java code will be like this

Caller.java

package com.phone.calller;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Callers extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button Phone = (Button) findViewById(R.id.call);
Phone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sIntent = new Intent(Intent.ACTION_CALL, Uri
.parse("tel:919894643826"));
startActivity(sIntent);
}
});
}
}


and the manifest.xml file will be like this


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phone.calller"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Callers"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

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

</manifest>

Have a good day.

The full source code

Download source

Monday, March 7, 2011

How to run a Runnable thread or UI thread in Android?

On the launching time of the application itselef the system creates a thread called "main" in the application. This main thread is also called as UI thread, it will only interact with the components of Android UI toolkit.

Here is an example for using the runnable thread in a click event, while clicking the image will be loaded, as it will take time to load the image, we can use the thread as shown below :

Java

public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bm = loadImage();
mImage.post(new Runnable() {
public void run() {
mImage.setImageBitmap(bm);
}
});
}
}).start();
}



Using Handler in Runnable thread


Here we are using the runnable thread using the handler. When we send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible.



Java

public class ProgressThread extends Activity implements Runnable {
private String result;
private TextView showResult;
private ProgressDialog progress;
@Override
public void onCreate(Bundle savedBundleInstance) {
super.onCreate(savedBundleInstance);
setContentView(R.layout.main);
showResult = (TextView) this.findViewById(R.id.main);
showResult.setText("Press any key to start calculation");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
progress = ProgressDialog.show(this, "Working..", "Calculation is going on...", true,
false);
Thread thread = new Thread(this);
thread.start();
return super.onKeyDown(keyCode, keyEvent);
}
public void run() {
result = MyClass.calculate(800).toString();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
showResult.setText(result);
}
};
}


The runnable thread can be called like this way too


Java

final Runnable runner = new Runnable()
{
public void run()
{
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};

handler.postDelayed(runner, 1000);


Otherwise we can use the original runnable thread that we are using in the java


Java

Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(runner);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

thread.start();


Have a good day.