Archive

Posts Tagged ‘application’

How to Kill Your Application

November 1, 2011 Leave a comment

If your want to kill your application, there are three ways AFAIK:

>> Method #1

android.os.Process.killProcess(android.os.Process.myPid());

>> Method #2

System.exit(0);

>> Method #3

finish(); // one provided method of 'Activity' class

There’s an old usual method is to use `ActivityManager.restartPackage()`; however, it’s already deprecated from API Level 3, suggesting not to use it anymore.

If you know any other ways, feel free to share!

Cheers,
Pete Houston

Create an application auto receiving new message (SMS)

July 14, 2011 27 comments

It’s quite a long time that I’ve been writing any new interesting tutorial. Today, I’ve got a little fever so I couldn’t step to workplace; so I decide to spend a little time to write a new tutorial.

The application we’re going to make today is a simple one that will receiving new messages automatically, notify and display them on a ListView. This is gonna be our simple screen:

SMS Auto Receiver

SMS Auto Receiver

A – Create the Project

Project Name: SMS Auto Receiver

Application Name: SMSAutoReceiver

Package Name: pete.android.study

Create Activity: MainActivity

Min SDK: 10

Click OK -> Done with creating project.

B – Sketch the Layout

The layout is pretty much the same as many previous articles on ListView in my blog.

+ One layout for main screen display, which is the list view

+ One layout for each item in the list view, which will be set to list view. This is where our SMS messages residing.

First, we start with layout for each item in list view.

1. List Item Layout

– First row determines the number of sender, I just make it into a LinearLayout with a constant TextView on the left with text “From: “ and right TextView gonna be used for setting incoming number.

– The second row displays the contents of message.

<?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:layout_height="wrap_content">

	<LinearLayout
		android:orientation="horizontal"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
	>
		<TextView
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="From: "
		/>

		<TextView
			android:id="@+id/tvNumber"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
		/>

	</LinearLayout>

	<TextView
		android:id="@+id/tvContent"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:singleLine="true"
		android:ellipsize="marquee"
	/>

</LinearLayout>

2. Main Layout

– Just a ListView, no more, no less!!!

C – Class Design – On the Idea

This is what I mapped from my mind.

Clss Diagram

Class Diagram

SmsInfo class: hold information about new message, which is also implement from interface Parcelable in order to be passed through by Intent.

SmsInfoAdapter class: the adapter manages content on ListView, extends from class ArrayAdapter<SmsInfo> for simplisticity.

SmsReceiver class: extends from class BroadcastReceiver, to handle the event when new message arrived, pass these messages to Intent and pass to launch MainActivity.

MainActivity class: is a actual class receiving list of new message (List<SmsInfo>) sending from

D – From Design to Code (w/ Passion)

1. SmsInfo.java

package pete.android.study;

import android.os.Parcel;
import android.os.Parcelable;

public class SmsInfo implements Parcelable {
	private String mNumber;
	private String mContent;

	public SmsInfo(String number, String content) {
		mNumber = number;
		mContent = content;
	}

	public SmsInfo(Parcel in) {
		String data[] = new String[2];
		in.readStringArray(data);
		mNumber = data[0];
		mContent = data[1];
	}

	public void setNumber(String number) {
		mNumber = number;
	}
	public String getNumber() {
		return mNumber;
	}

	public void setContent(String content) {
		mContent = content;
	}
	public String getContent() {
		return mContent;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeStringArray(new String[] {
			mNumber, mContent
		});

	}

	public static final Parcelable.Creator<SmsInfo> CREATOR = new Parcelable.Creator<SmsInfo> () {

		@Override
		public SmsInfo createFromParcel(Parcel source) {

			return new SmsInfo(source);
		}

		@Override
		public SmsInfo[] newArray(int size) {

			return new SmsInfo[size];
		}

	};
}

2. SmsInfoAdapter.java

package pete.android.study;

import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SmsInfoAdapter extends ArrayAdapter<SmsInfo> {

	public SmsInfoAdapter(Activity a, List<SmsInfo> list) {
		super(a, 0, list);

	}

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

		ViewHolder holder = null;
		if(convertView == null) {
			Activity a = (Activity)getContext();
			LayoutInflater inflater = a.getLayoutInflater();
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.listitem, null);
			holder.tvNumber = (TextView)convertView.findViewById(R.id.tvNumber);
			holder.tvContent = (TextView)convertView.findViewById(R.id.tvContent);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder)convertView.getTag();
		}

		SmsInfo entry = getItem(pos);
		if(entry != null) {
			holder.tvNumber.setText(entry.getNumber());
			holder.tvContent.setText(entry.getContent());
		}

		return convertView;
	}

	static class ViewHolder {
		TextView tvNumber;
		TextView tvContent;
	}
}

3. SmsReceiver.java

package pete.android.study;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
import pete.android.study.SmsInfo;

public class SmsReceiver extends BroadcastReceiver {
	static ArrayList<SmsInfo> listSms = new ArrayList<SmsInfo>();
	@Override
	public void onReceive(Context context, Intent intent) {
		// get SMS map from intent
        Bundle extras = intent.getExtras();
        // a notification message
        String messages = "";
        if ( extras != null ) {
            // get array data from SMS
            Object[] smsExtra = (Object[]) extras.get( "pdus" ); // "pdus" is the key

            for ( int i = 0; i < smsExtra.length; ++i ) {
            	// get sms message
            	SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
            	// get content and number
            	String body = sms.getMessageBody();
            	String address = sms.getOriginatingAddress();
            	// create display message
            	messages += "SMS from " + address + " :\n";
            	messages += body + "\n";

            	// store in the list
                listSms.add(new SmsInfo(address, body));
            }

            // better check size before continue
            if(listSms.size() > 0) {
            	// notify new arriving message
            	Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
            	// set data to send
	            Intent data = new Intent(context, MainActivity.class);
	            // new activity
	            data.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

	            data.putParcelableArrayListExtra("ListSMS", listSms);
	            // start
	            context.startActivity(data);
            }
        }
    }
}

4. MainActivity.java

package pete.android.study;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {
    ListView mListData;

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

        mListData = (ListView)findViewById(R.id.lvData);
        // receive list incoming messages
        ArrayList<SmsInfo> listSms = getIntent().getParcelableArrayListExtra("ListSMS");
        // check condition
        if(listSms != null && listSms.size() > 0) {
        	// set dat to list
        	SmsInfoAdapter adapter = new SmsInfoAdapter(this, listSms);
	        mListData.setAdapter(adapter);
        }
    }
}

E – Additional Config

We need to set uses-permission to receive SMS and register our SMSReceiver in order to make it work.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pete.android.study"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
	<uses-permission android:name="android.permission.RECEIVE_SMS" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".SmsReceiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

F – Get the Sample Project by Pete

Click to browse Trunk from GoogleCode.

 

G – Final Words

– Hope you enjoy and learn something from this article 🙂

– Feel free to suggest, comment below!

 

Cheers,

Pete Houston

Set icon for Android application

July 13, 2011 1 comment

It’s very simple! What you need to do is just to specify the icon you want in AndroidManifest.xml

Set Application Icon

Set Application Icon

Remember to put the icon (should be: PNG or JPG) in /drawable directory.

Hope you like it!

 

Cheers,

Pete Houston

 

Create Application Launcher as a list

June 12, 2011 38 comments

This is how Google Android default Application screen looks like:

Default Android Application Launcher

Default Android Application Launcher

It’s a grid view and when you click on one of those, the corresponding activity is launched.

Ok, so now I’ll guide you how to create a similar one but in a list view. Here the screenshot:

Application Viewer

Application Viewer

A – What Does It Do?

– All the installed application on the machine is displayed with their icons, label names and package names.

– When an item is clicked the corresponding activity is launched.

– If the item does not exist, a small message notification will display. (it might not happen, lol)

– If the item exist, but current user does not have the permission to launch, well, just do nothing. (it’s kinda fun on slow emulator :D)

B – Create the Project

Project Name: Application Viewer

Build Target: Android 2.3.3 (the latest one at this time, well, I like it though)

Application Name: Application Viewer

Package Name: pete.android.study

Create Activity: MainActivity

Min SDK: 10

C – Sketch the Layout

Like old times (my previous post), we need two layouts:

+ one layout for each item in the list view

+ one layout for main list view display

1. List Item Layout (/res/layout/layout_appinfo.xml)

– You may want to refer to my previous tutorial on creating a PhoneBook, because the layout is much alike. I’m feeling lazy to describe it again…zzz

<?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="?android:attr/listPreferredItemHeight"
  android:padding="5dip"  
  >
  
  <ImageView
      android:id="@+id/ivIcon"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:layout_marginRight="5dip"
      android:scaleType="center"
  />
  
  <LinearLayout
      android:orientation="vertical"
      android:layout_width="0dip"
      android:layout_height="fill_parent" 
      android:layout_weight="1"     
  >
  
      <TextView
          android:id="@+id/tvName"
          android:layout_width="fill_parent"
          android:layout_height="0dip"
          android:layout_weight="1"
          android:gravity="center_vertical"          
      />
      
      <TextView
          android:id="@+id/tvPack"
          android:layout_width="fill_parent"
          android:layout_height="0dip"
          android:layout_weight="1"
          android:singleLine="true"
          android:ellipsize="marquee"          
      />
  
  </LinearLayout>
  
  
</LinearLayout>

2. Main Layout (/res/layout/layout_main.xml)

– Just one single list view to apply.

<?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:layout_height="fill_parent"
    >

	<ListView
		android:id="@+id/lvApps"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"		
	/>

</LinearLayout>

D – Class Design: On the Idea

This is a quite complicated shit of class diagram. I’m just thinking of making it more details.

Application Viewer - Class Diagram

Application Viewer - Class Diagram

MainActivity: the entry of the program, we will load list view here, create and set adapter to list view, and handle OnItemClickListener (which is from AdapterView) in list view.

AppInfoAdapter: the adapter inherits from BaseAdapter to handle list item, we need to handle things in getView() (loading controls from resources, set them appropriate values,  get application info meta data..).

Utilities: to support

+ get installed application list.

+ launch an activity.

E – From Design to Coding (w/ Passion)

1. AppInfoAdapter: (AppInfoAdapter.java)

package pete.android.study;

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class AppInfoAdapter extends BaseAdapter {
	private Context mContext;
	private List mListAppInfo;
	private PackageManager mPackManager;

	public AppInfoAdapter(Context c, List list, PackageManager pm) {
		mContext = c;
		mListAppInfo = list;
		mPackManager = pm;
	}

	@Override
	public int getCount() {
		return mListAppInfo.size();
	}

	@Override
	public Object getItem(int position) {
		return mListAppInfo.get(position);
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// get the selected entry
		ApplicationInfo entry = mListAppInfo.get(position);

		// reference to convertView
		View v = convertView;

		// inflate new layout if null
		if(v == null) {
			LayoutInflater inflater = LayoutInflater.from(mContext);
			v = inflater.inflate(R.layout.layout_appinfo, null);
		}

		// load controls from layout resources
		ImageView ivAppIcon = (ImageView)v.findViewById(R.id.ivIcon);
		TextView tvAppName = (TextView)v.findViewById(R.id.tvName);
		TextView tvPkgName = (TextView)v.findViewById(R.id.tvPack);

		// set data to display
		ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
		tvAppName.setText(entry.loadLabel(mPackManager));
		tvPkgName.setText(entry.packageName);

		// return view
		return v;
	}
}

2. Utilities: (Utilities.java)

package pete.android.study;

import java.util.List;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.widget.Toast;

public class Utilities {

	/*
	 * Get all installed application on mobile and return a list
	 * @param	c	Context of application
	 * @return	list of installed applications
	 */
	public static List getInstalledApplication(Context c) {
		return c.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
	}

	/*
	 * Launch an application
	 * @param	c	Context of application
	 * @param	pm	the related package manager of the context
	 * @param	pkgName	Name of the package to run
	 */
	public static boolean launchApp(Context c, PackageManager pm, String pkgName) {
		// query the intent for lauching
		Intent intent = pm.getLaunchIntentForPackage(pkgName);
		// if intent is available
		if(intent != null) {
			try {
				// launch application
				c.startActivity(intent);
				// if succeed
				return true;

			// if fail
			} catch(ActivityNotFoundException ex) {
				// quick message notification
				Toast toast = Toast.makeText(c, "Application Not Found", Toast.LENGTH_LONG);
				// display message
				toast.show();
			}
		}
		// by default, fail to launch
		return false;
	}
}

3. MainActivity: (MainActivity.java)

package pete.android.study;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
    private ListView mListAppInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set layout for the main screen
        setContentView(R.layout.layout_main);

        // load list application
        mListAppInfo = (ListView)findViewById(R.id.lvApps);
        // create new adapter
        AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());
        // set adapter to list view
        mListAppInfo.setAdapter(adapter);
        // implement event when an item on list view is selected
        mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
        	@Override
        	public void onItemClick(AdapterView parent, View view, int pos, long id) {
        		// get the list adapter
        		AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
        		// get selected item on the list
        		ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
        		// launch the selected application
        		Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
        	}
		});
    }
}

F – Note

– Using the tip of retrieving the list of installed application.

– Using the tip of launching an activity from another.

– Performance is not so good :), of course. You can think of better solution than mine!

– The code is toooo simple, I guess!

G – Get the Sample Project by Pete

Pick your favorite file hosting server: Mediafire | Rapidshare | Megaupload

H – Final Words

– Have you learned something?

– Is it easy to understand?

– Make sure you practice day by day with me :D, it’s fun, isn’t it?

– Hope you enjoy it!

Cheers,

Pete Houston

Display application fullscreen

June 12, 2011 1 comment

There will be times you want your application to display in full, that is, full-screen.

Full-Screen

Full-Screen

The trick is very simple 😀

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set full-screen
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
    }
}

Hope you enjoy it!

Cheers,
Pete Houston