Display incoming SMS messages in Android

Hi guys,

In the past, we have seen how a Broadcast Receiver can be used to listen to certain events and in turn notify the user when the particular event occurs. In general, a broadcast originates from the system as well as applications.

It is important to register a broadcast receiver for a particular action. One of the ways of registering the same is by using the receiver tag in the AndroidManifest.xml file. Through this post, we will learn how to listen to incoming SMS text messages in Android using a broadcast receiver.

Pre-requisites: Eclipse IDE, Android SDK

Launch Eclipse IDE and in any of your existing Android application projects create a new class called MySMSApp and add the following code.

MySMSApp.java

package com.example;

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

public class MySMSApp extends BroadcastReceiver {

	public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (intent.getAction().equals(ACTION)){ 
			Bundle bundle = intent.getExtras();
			if (bundle != null){
				Object[] pdus = (Object[]) bundle.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];
				for (int i = 0; i < pdus.length; i++){
					messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
				for (SmsMessage message : messages){
					
					String strMessageFrom = message.getDisplayOriginatingAddress();
					String strMessageBody = message.getDisplayMessageBody();

					Toast.makeText(context, "SMS Message received from:" +strMessageFrom, Toast.LENGTH_LONG).show();
					Toast.makeText(context, "SMS Message content" +strMessageBody, Toast.LENGTH_LONG).show();

				}
			}    
		} 
	}

}

Once we have implemented our receiver class, it is important to register the same in the AndroidManifest.xml file as follows.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.SomeDummyActivity"
            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 for SMS -->
        <receiver android:name=".MySMSApp">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Save all changes. Make sure no errors are present. Run the application on an Android device. The next time you get an SMS message, you should see the following output!

output

That’s it for this Android tip. Still lots more to come…! 🙂

Implement DialogFragment in Android

Hello everyone!

Users often need to make certain choices while using an application. A dialog resembles a small window that helps the user to make a decision or enter any additional information. If an application consists of a number of dialogs, one would possibly go ahead and create multiple “Yes/No” dialogs. However, if fragments are used within your Activity, then you need to use DialogFragment in order to present a fragment as a dialog (window). A simple Dialog won’t help in this case as it has nothing to do with the fragment’s life-cycle.

DialogFragments and Fragments are made available in the support library which makes the class usable in all currently used versions of Android. On the whole, a DialogFragment is pretty similar to a Dialog. It’s just wrapped inside a fragment. Through this post, we will learn how to implement a DialogFragment in Android.

Pre-requisites: Eclipse IDE, Android SDK

In any of your existing Android projects, creating a new Activity class called TestDialogFragmentActivity with package name com.example and add the following code.

TestDialogFragmentActivity.java

package com.example;

import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestDialogFragmentActivity extends FragmentActivity {

	private Button btnOpenFragment;
	FragmentManager fm = getSupportFragmentManager();

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

		btnOpenFragment = (Button) findViewById(R.id.btnfragment);
		btnOpenFragment.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
			      MyDialogFragment dialogFragment = new MyDialogFragment();
			      dialogFragment.show(fm, "Dialog Fragment");
			}
		});

	}
}

Now, let’s implement the DialogFragment class for the same. Create a new class called MyDialogFragment and add the following code.

MyDialogFragment.java

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyDialogFragment extends DialogFragment {


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		View rootView = inflater.inflate(R.layout.dialog_fragment, container,false);
        getDialog().setTitle("DialogFragment Example");        
       
        return rootView;
	}	
}

The layout files would be as follows,

activity_fragment.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <Button
        android:id="@+id/btnfragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/dialogFragment" />

</RelativeLayout>

dialog_fragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:text="@string/txtFragment" />

</RelativeLayout>

strings.xml

    <string name="txtFragment">Hi. This is a dialog fragment</string>
    <string name="dialogFragment">Open DialogFragment</string>

Finally, make sure no errors are present. Save all changes. Run the application on an Android device and you should see the following output!

output_1

output_2

Reference: Android DialogFragment

Getting started with Android Wear!

Hello everyone!

Android wear is a platform developed by Google for wearable devices. It was launched in the month of March 2014 as a developer preview along with partner companies such as Motorola, Samsung, LG etc. Android Wear is basically an operating system designed primarily for smartwatches and other wearables. It integrates Google Now functionality and mobile notifications into the screen of a wearable device.

Through this post, we will learn how to get started with using Android Wear. We would be creating a sample program to display wearable style notifications!

Pre-requisites: Eclipse IDE, Android SDK (Target SDK: Android 4.4W)

Step 1: Download Android Wear SDK

In order to start creating wearable applications, one needs to download and install the Wearable SDK. Launch the SDK Manager application and download the latest version of the SDK.

sdk_manager

Step 2: Create new Android Wear project

Create a new Android application project called AndroidWearHelloWorld with package name com.app.hellowear. Choose the target SDK as Android 4.4W.

Next, add the following code in your Activity class.

MainActivity.java


import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.NotificationManagerCompat;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);	
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);


        // Create a big text style for the notification
        NotificationCompat.BigTextStyle notificationPageStyle = new NotificationCompat.BigTextStyle();
        secondPageStyle.setBigContentTitle("Test Message!")
        .bigText("This is a really long message...");

        PendingIntent actionPendingIntent =
                PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class),
                        PendingIntent.FLAG_CANCEL_CURRENT);

        // Create the action
        NotificationCompat.Action action =
                new NotificationCompat.Action.Builder(R.drawable.ic_launcher,
                        getString(R.string.test), actionPendingIntent)
                        .build();

        // Build the notification and add the action via WearableExtender
        Notification wearableNotification =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setStyle(notificationPageStyle)
                        .extend(new WearableExtender().addAction(action))
                        .build();
        
        notificationManagerCompat.notify(2, wearableNotification);

	}
 }

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidWearHelloWorld</string>
    <string name="hello_world">Go to notification screen</string>
    <string name="test">You have a new message!</string>   
</resources>

Finally, save all changes and run the application on an Android Wear compatible virtual device. If no errors occur then you should see the following output!

output_1

output_2

Lot’s more on Android Wear in my upcoming posts. Stay tuned! 🙂

Reference: Android Wear Notifications