Contoh Aplikasi SMS Sederhana pada Android


Kebetulan hari ini proyek sudah selesai, jadi ada waktu buat ngeblog. Baiklah, langsung saja, kali ini saya akan sharing source code android saya mengenai aplikasi SMS Sederhana pada Android.

Sebelumnya, ada beberapa referensi yang mungkin bisa jadi tambahan untuk pengetahuan mengenai pembuatan aplikasi SMS pada android

Referensinya :

http://www.mkyong.com/android/how-to-send-sms-message-in-android/
http://developer.android.com/reference/android/telephony/SmsManager.html
http://www.c-sharpcorner.com/UploadFile/ef3808/simple-sms-application-in-android/

Source codenya :
MainActivity.java

package com.contohaplikasismssederhana;

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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		((Button) findViewById(R.id.tombolbuatpesan))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						MainActivity.this.startActivity(new Intent(
								MainActivity.this, BuatPesan.class));
					}
				});
		((Button) findViewById(R.id.tombolpesankeluar))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						Intent click = new Intent(MainActivity.this,
								DataPesan.class);
						click.putExtra("tipepesan", "sent");
						startActivity(click);
					}
				});
		((Button) findViewById(R.id.tombolpesanmasuk))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						Intent click = new Intent(MainActivity.this,
								DataPesan.class);
						click.putExtra("tipepesan", "inbox");
						startActivity(click);
					}
				});

		((Button) findViewById(R.id.tombolexit))
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_MAIN);
						intent.addCategory(Intent.CATEGORY_HOME);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(intent);
						System.exit(0);
					}
				});
	}

}

BuatPesan.java

package com.contohaplikasismssederhana;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class BuatPesan extends Activity {
	EditText nomorKontak, text;

	// contact picker
	private static final int CONTACT_PICKER_RESULT = 1001;

	// phonecontact
	public void doLaunchContactPicker(View view) {
		Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, uri);
		startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		String phone = "";
		Cursor contacts = null;
		try {
			if (resultCode == RESULT_OK) {
				switch (requestCode) {
				case CONTACT_PICKER_RESULT:

					// gets the uri of selected contact
					Uri result = data.getData();
					// get the contact id from the Uri (last part is contact
					// id)
					String id = result.getLastPathSegment();
					// queries the contacts DB for phone no
					contacts = getContentResolver().query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone._ID + "=?",
							new String[] { id }, null);
					// gets index of phone no
					int phoneIdx = contacts.getColumnIndex(Phone.DATA);
					if (contacts.moveToFirst()) {
						// gets the phone no
						phone = contacts.getString(phoneIdx);
						EditText phoneTxt = (EditText) findViewById(R.id.nomorHp);
						// assigns phone no to EditText field phoneno
						phoneTxt.setText(phone);
					} else {
						Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
					}

					break;

				}

			} else {
				// gracefully handle failure
				Toast.makeText(BuatPesan.this, R.string.belumdipilih,
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		} finally {
			if (contacts != null) {
				contacts.close();
			}
		}
	}

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.buatpesan);

		final ImageButton send = (ImageButton) findViewById(R.id.send);

		text = (EditText) findViewById(R.id.smsBox);
		nomorKontak = (EditText) findViewById(R.id.nomorHp);

		// fungsi untuk menampilkan isi pesan saat akan diteruskan
		Intent i = getIntent();
		if (i.getStringExtra("message") != null) {
			text.setText(i.getStringExtra("message"));
		}

		send.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String pesan = text.getText().toString();
				String nomor = nomorKontak.getText().toString();
				if (pesan.length() > 0 && nomor.length() > 0) {
					try {
						// proses kirim sms
						SmsManager sms = SmsManager.getDefault();
						sms.sendTextMessage(nomor, null, pesan, null, null);

						// proses simpan sms yang terkirim
						ContentValues values = new ContentValues();
						values.put("address", nomor);
						values.put("body", pesan);
						getContentResolver().insert(
								Uri.parse("content://sms/sent"), values);

						Toast.makeText(BuatPesan.this,
								"Pesan berhasil dikirim", Toast.LENGTH_SHORT)
								.show();
						finish();
					} catch (Exception e) {
						Toast.makeText(BuatPesan.this, "Pesan gagal dikirim",
								Toast.LENGTH_SHORT).show();
						e.printStackTrace();
					}

				} else {
					Toast.makeText(BuatPesan.this,
							"Nomor atau Isi Pesan Masing Kosong",
							Toast.LENGTH_SHORT).show();
				}

			}
		});

	}

}

DataPesan.java

package com.contohaplikasismssederhana;

import java.util.Date;
import java.text.DateFormat;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;

public class DataPesan extends Activity {
	private SimpleCursorAdapter dataAdapter;

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

		displayListView();

	}

	private void displayListView() {
		Intent i = getIntent();
		Uri uriSMS = Uri
				.parse("content://sms/" + i.getStringExtra("tipepesan"));
		Cursor cursor = getContentResolver().query(uriSMS, null, null, null,
				null);

		String[] columns = new String[] { "address", "body", "date" };

		int[] to = new int[] { R.id.pengirim, R.id.isipesan, R.id.waktu };

		dataAdapter = new SimpleCursorAdapter(this, R.layout.pesan_row, cursor,
				columns, to, 0);

		ListView listView = (ListView) findViewById(R.id.listView1);

		dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			@Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {

				// ubah nomer hape dengan nama yang ada dikontak
				if (columnIndex == 2) {
					TextView tv = (TextView) view;
					String pengirimDB = cursor.getString(cursor
							.getColumnIndex("address"));
					// get contact name
					Uri contactUri = Uri.withAppendedPath(
							ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
							Uri.encode(pengirimDB));
					Cursor cur = getContentResolver().query(contactUri, null,
							null, null, null);
					ContentResolver contect_resolver = getContentResolver();

					int size = cur.getCount();
					if (size > 0 && cur != null) {
						for (int i = 0; i < size; i++) {
							cur.moveToPosition(i);

							String id1 = cur.getString(cur
									.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

							Cursor phoneCur = contect_resolver
									.query(contactUri,
											null,
											ContactsContract.CommonDataKinds.Phone.CONTACT_ID
													+ " = ?",
											new String[] { id1 }, null);

							if (phoneCur.moveToFirst()) {
								String namaKontak = phoneCur.getString(phoneCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
								phoneCur.close();
								tv.setText(namaKontak);
							} else {
								tv.setText(pengirimDB);
							}

						}

						cur.close();
					} else {
						tv.setText(pengirimDB);
					}

					return true;
				}

				// konversi tanggal
				if (columnIndex == 4) {
					TextView tv = (TextView) view;
					String waktu = cursor.getString(cursor
							.getColumnIndex("date"));
					long l = Long.parseLong(waktu);
					Date d = new Date(l);
					String date = DateFormat.getDateInstance(DateFormat.LONG)
							.format(d);
					String time = DateFormat.getTimeInstance().format(d);
					String view_waktu = date + " " + time;

					tv.setText(view_waktu);

					return true;
				}

				return false;
			}
		});

		// menampilkan daftar pesan
		listView.setAdapter(dataAdapter);

		// jika di pesan di klik, maka akan dialihkan ke lihat pesan secara full
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> listView, View view,
					int position, long id) {
				// Get the cursor, positioned to the corresponding row in the
				// result set
				Cursor cursor = (Cursor) listView.getItemAtPosition(position);

				// Get the state's capital from this row in the database.
				String view_pengirim = cursor.getString(cursor
						.getColumnIndexOrThrow("address"));
				String view_isipesan = cursor.getString(cursor
						.getColumnIndexOrThrow("body"));

				String waktu = cursor.getString(cursor
						.getColumnIndexOrThrow("date"));

				// konversi tanggal
				long l = Long.parseLong(waktu);
				Date d = new Date(l);
				String date = DateFormat.getDateInstance(DateFormat.LONG)
						.format(d);
				String time = DateFormat.getTimeInstance().format(d);
				String view_waktu = date + " " + time;

				String view_idpesan = cursor.getString(cursor
						.getColumnIndexOrThrow("_id"));
				String view_thread = cursor.getString(cursor
						.getColumnIndexOrThrow("thread_id"));
				Intent click = new Intent(DataPesan.this, LihatPesan.class);

				// get contact name
				Uri contactUri = Uri.withAppendedPath(
						ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
						Uri.encode(view_pengirim));
				Cursor cur = getContentResolver().query(contactUri, null, null,
						null, null);
				ContentResolver contect_resolver = getContentResolver();

				int size = cur.getCount();
				if (size > 0 && cur != null) {
					for (int i = 0; i < size; i++) {
						cur.moveToPosition(i);

						String id1 = cur.getString(cur
								.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

						Cursor phoneCur = contect_resolver
								.query(contactUri,
										null,
										ContactsContract.CommonDataKinds.Phone.CONTACT_ID
												+ " = ?", new String[] { id1 },
										null);

						if (phoneCur.moveToFirst()) {
							String namaKontak = phoneCur.getString(phoneCur
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
							phoneCur.close();
							click.putExtra("no", namaKontak);
						} else {
							click.putExtra("no", view_pengirim);
						}

					}

					cur.close();
				} else {
					click.putExtra("no", view_pengirim);
				}

				// kirim data ke view pesan
				click.putExtra("msg", view_isipesan);
				click.putExtra("idpesan", view_idpesan);
				click.putExtra("idthread", view_thread);
				click.putExtra("date", view_waktu);
				Intent i = getIntent();
				click.putExtra("asal", i.getStringExtra("tipepesan"));
				startActivity(click);

			}
		});

	}

	@Override
	public void onBackPressed() {
		Intent link = new Intent(DataPesan.this, MainActivity.class);
		startActivity(link);
		finish();

	}

}

LihatPesan.java

package com.contohaplikasismssederhana;

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

public class LihatPesan extends Activity {
	TextView number, date, msg;
	Button forward, hapus;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lihatpesan);
		number = (TextView) findViewById(R.id.tvNumber);
		date = (TextView) findViewById(R.id.tvDate);
		msg = (TextView) findViewById(R.id.tvMsg);
		forward = (Button) findViewById(R.id.btFrd);
		hapus = (Button) findViewById(R.id.hapus);
	}

	@Override
	protected void onStart() {
		super.onStart();
		Intent i = getIntent();
		number.setText(i.getStringExtra("no"));
		date.setText(i.getStringExtra("date"));
		msg.setText(i.getStringExtra("msg"));

		forward.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent click = new Intent(LihatPesan.this, BuatPesan.class);
				click.putExtra("message", msg.getText());
				startActivity(click);

			}
		});
		hapus.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Dialogs.showConfirmation(LihatPesan.this,
						R.string.hapuspesan_dialog,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int which) {
								Intent i = getIntent();
								String id_pesan_hapus = i
										.getStringExtra("idpesan");
								String id_thread_hapus = i
										.getStringExtra("idthread");

								// hapus pesan
								Uri deleteUri = Uri.parse("content://sms");

								getContentResolver()
										.delete(deleteUri,
												"thread_id=? and _id=?",
												new String[] {
														String.valueOf(id_thread_hapus),
														String.valueOf(id_pesan_hapus) });

								finish();
								Toast.makeText(LihatPesan.this,
										"Pesan Terhapus", Toast.LENGTH_SHORT)
										.show();

								// redirect data pesan
								onBackPressed();
							}
						});
			}
		});

	}

	@Override
	public void onBackPressed() {
		Intent link = new Intent(LihatPesan.this, DataPesan.class);
		Intent i = getIntent();
		link.putExtra("tipepesan", i.getStringExtra("asal"));
		startActivity(link);
	}

}

Dialogs.java


package com.contohaplikasismssederhana;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

public class Dialogs {

	public static void showConfirmation(Context context, int message,
			OnClickListener onYes) {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				context);

		// set title
		alertDialogBuilder.setTitle(R.string.confirmation);

		// set dialog message
		alertDialogBuilder
				.setMessage(message)
				.setCancelable(false)
				.setPositiveButton("Ya", onYes)
				.setNegativeButton("Tidak",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});

		// create alert dialog
		AlertDialog alertDialog = alertDialogBuilder.create();

		// show it
		alertDialog.show();
	}

}

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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<Button
android:id="@+id/tombolbuatpesan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="@string/buatpesan" />

<Button
android:id="@+id/tombolpesanmasuk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/tombolpesankeluar"
android:layout_below="@+id/tombolbuatpesan"
android:layout_marginTop="31dp"
android:text="@string/pesanmasuk" />

<Button
android:id="@+id/tombolexit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tombolpesankeluar"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:text="@string/keluar" />

<Button
android:id="@+id/tombolpesankeluar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tombolpesanmasuk"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="@string/pesankeluar" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="@string/intro"
android:textStyle="italic" />

</RelativeLayout>

buatpesan.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<LinearLayout
android:id="@+id/boxkontak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp" >

<EditText
android:id="@+id/nomorHp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="11.10"
android:ems="10"
android:inputType="number" />

<ImageButton
android:id="@+id/pick"
style="@drawable/phonebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.14"
android:background="@drawable/phonebook"
android:contentDescription="@string/datakontak"
android:onClick="doLaunchContactPicker" />
</LinearLayout>

<LinearLayout
android:id="@+id/boxsms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/boxkontak"
android:layout_marginTop="@dimen/duapuluh"
android:orientation="horizontal" >

<EditText
android:id="@+id/smsBox"
android:layout_width="263dp"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/lima"
android:layout_marginTop="@dimen/sepuluh"
android:ems="10"
android:hint="@string/pesanhint"
android:inputType="textMultiLine" >

<requestFocus />
</EditText>

<ImageButton
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/send"
android:contentDescription="@string/buatpesan" />

</LinearLayout>

</RelativeLayout>

lihatpesan.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/sepuluh" >

<LinearLayout
android:layout_width="match_parent"
android:layout_height="360dp"
android:layout_above="@+id/linearLayout1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp" >

<TextView
android:id="@+id/tvMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >

<Button
android:id="@+id/btFrd"
android:layout_width="147dp"
android:layout_height="wrap_content"
android:layout_weight="0.90"
android:text="@string/teruskan" />

<Button
android:id="@+id/hapus"
android:layout_width="158dp"
android:layout_height="wrap_content"
android:text="@string/hapuspesan" />
</LinearLayout>

<TextView
android:id="@+id/tvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tvNumber"
android:layout_below="@+id/tvNumber"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

listpesan.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="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>

pesan_row.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:orientation="vertical"
android:padding="6dip" >

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

<TextView
android:id="@+id/waktu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/pengirim"
android:layout_below="@+id/pengirim"
android:text="TextView" />

<TextView
android:id="@+id/isipesan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/waktu"
android:layout_below="@+id/waktu"
android:text="TextView" />

</RelativeLayout>

strings.xml

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

<string name="app_name">SMS Sederhana</string>
<string name="belumdipilih">Kontak Belum di Pilih</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="intro">Contoh Aplikasi SMS Sederhana by herupurwito.wordpress.com</string>
<string name="buatpesan">Buat Pesan</string>
<string name="pesanmasuk">Pesan Masuk</string>
<string name="pesankeluar">Pesan Keluar</string>
<string name="keluar">Keluar</string>
<string name="hapuspesan_dialog">Apakah Anda Yakin Akan Menghapus SMS ini?</string>
<string name="pesanhint">Ketikkan Pesan Anda disini</string>
<string name="datakontak">Data Kontak</string>
<string name="pesan">Pesan</string>
<string name="teruskan">Teruskan</string>
<string name="hapuspesan">Hapus Pesan</string>
<string name="confirmation">Konfirmasi</string>

</resources>

dimens.xml


<resources>

<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="duapuluh">20px</dimen>
<dimen name="sepuluh">10px</dimen>
<dimen name="lima">5px</dimen>

</resources>

AndroidManifest.xml

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

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.contohaplikasismssederhana.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>
<activity
android:name="com.contohaplikasismssederhana.BuatPesan"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.contohaplikasismssederhana.LihatPesan"
android:label="@string/app_name" >

</activity>
<activity
android:name="com.contohaplikasismssederhana.DataPesan"
android:label="@string/app_name" >
</activity>
</application>

</manifest>

Download Full Source Code
Github
Dropbox
Demo APK

Screenshoot
1_halamanutama

2_halamanbuatpesan

3_halaman_contact_picker

4_list_sms

5_lihatsms

6_hapuSMS

7_teruskan_SMS

About these ads

49 thoughts on “Contoh Aplikasi SMS Sederhana pada Android

  1. bang!!! kl untuk kode forward sms gmn ya???

    makasih

    • ada di file LihatPesan.java di baris 37 itu kode buat forward pesan,

      click.putExtra("message", msg.getText());

      nah, kode itu buat ngambil pesan yang akan di forward

      • ooo gthu…sip

        kl dikembangkan lg sistem replay sms!!! jd untuk mendeteksi kl ada sms baru yg masuk kemudian secara automatis isi sms tesebut di copy dan langsung diteruskan kenomor yg dituju. caranya gmn bang??

        makasih & salam sukses

      • sistemnya sama kayak pesan yang diteruskan, cuma yang diambil nomer teleponnya bukan isipesannya..
        jadi ->

        click.putExtra("number", msg.getText());
      • ok…tak coba dl.

        makasih

  2. bang!!! kl untuk rekam suara obrolan tlp di hp yg kemudian tersimpan automatis ke memori/mmc di folder yg udh di sediakan dalam format wav/amr/mp3 thu gmn ya???

    makasi & salam sukses

  3. kl untuk tombol send thu dibuat automatis tanpa harus diklik tp langsung mengirim setelah forward number+text message selesai dibuat thu caranya gimana ya???

    makasih

  4. Mas, bagaimana jika saya menggunakan Eclipse di Ubuntu, lalu ketika mengamalkan tutorial akang ini saya mendapatkan pesan galat:

    R cannot be resolved to a variable

    pada setiap baris yang berisi R. Folder gen/ saya tidak ada R.java. Bagaimana cara menyelesaikannya? Sebagai informasi, Eclipse saya datang bersama ADT Bundle Linux yang empat ratus MB itu. Saya unduh dari Google. Saya tidak menginstal Eclipse dari repo yang saya tambahi ADT karena gagal terus.

  5. gan kl untuk baca kontak gitu source code nya gimana ya, jd kita gx usah masukin nomor tlp, jd tinggal baca aja dr kontak gitu. gimana caranya ya?
    mohon bantuannya ^^

  6. gan, kok gak bisa dihapus ya?

  7. bro …
    saya kan pake condingan ini ..
    tapi modifikasi pake Vigenere Chipher ..
    kenapa ya, ci penerima sms ga bisa ngbaca char acii ..
    tolong dong bantuannya …!!

  8. kenapa pesan ga bisa di hpus gan??

  9. kak heru ko saya coba di kopas ko tiap tanda ” R ” ko di salahin ya ?
    kenapa ?

    ((Button) findViewById(R.id.tombolpesankeluar))
    .setOnClickListener(new OnClickListener() {

  10. yang saya ko pas di buka aplikasinya

    unfortunately,sms sederhana
    has stoped

  11. gan, saya coba kodingannya di android 14, tapi ada error di class dataPesan bagian :

    import android.support.v4.widget.SimpleCursorAdapter;

    ini karena library nya ga sesuai atau gimana ya? mohon pencerahannya…

    terima kasih..

  12. gan, yang diatas itu kode bagian milih kontak terus tampilin di edittext nya yang mana?

    • ada di file BuatPesan.java, baris 58

      if (contacts.moveToFirst()) {
                              // gets the phone no
                              phone = contacts.getString(phoneIdx);
                              EditText phoneTxt = (EditText) findViewById(R.id.nomorHp);
                              // assigns phone no to EditText field phoneno
                              phoneTxt.setText(phone);
                          } 
      
      • gan, ini ane ngikutin yg punya agan buat list inbox nya, tapi kok belum bisa ya? kira2 masalah dimananya?
        (ane bikin 1 layout tambahan juga kayak unya agan: pessan_row)

        package com.example.smsencryption;

        import android.app.Activity;
        import android.content.ContentResolver;
        import android.content.Intent;
        import android.database.Cursor;
        import android.net.Uri;
        import android.os.Bundle;
        import android.provider.ContactsContract;
        import android.support.v4.widget.SimpleCursorAdapter;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.ListView;
        import android.widget.TextView;
        import android.widget.AdapterView.OnItemClickListener;

        public class list_inbox extends Activity{
        private SimpleCursorAdapter dataAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_inbox);

        displayListView();

        }

        private void displayListView() {
        Intent i = getIntent();
        Uri uriSMS = Uri
        .parse(“content://sms/” + i.getStringExtra(“tipepesan”));
        Cursor cursor = getContentResolver().query(uriSMS, null, null, null,
        null);
        String[] columns = new String[] { “address”, “body” };
        int[] to = new int[] { R.id.txtPhone, R.id.txtMesEncrypt };
        dataAdapter = new SimpleCursorAdapter(this, R.layout.pesan_row, cursor, columns, to, 0);

        final ListView listView = (ListView) findViewById(R.id.listInbox);

        dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor,int columnIndex) {

        // ubah nomer hp dengan nama yang ada dikontak
        if (columnIndex == 2) {
        TextView tv = (TextView) view;
        String pengirimDB = cursor.getString(cursor.getColumnIndex(“address”));
        // get contact name
        Uri contactUri = Uri.withAppendedPath(
        ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(pengirimDB));
        Cursor cur = getContentResolver().query(contactUri, null, null, null, null);
        ContentResolver contect_resolver = getContentResolver();

        int size = cur.getCount();
        if (size > 0 && cur != null) {
        for (int i = 0; i < size; i++) {
        cur.moveToPosition(i);

        String id1 = cur.getString(cur
        .getColumnIndexOrThrow(ContactsContract.Contacts._ID));

        Cursor phoneCur = contect_resolver.query(contactUri,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",new String[] { id1 }, null);

        if (phoneCur.moveToFirst()) {
        String namaKontak = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        phoneCur.close();
        tv.setText(namaKontak);
        } else {
        tv.setText(pengirimDB);
        }

        }

        cur.close();
        } else {
        tv.setText(pengirimDB);
        }

        return true;
        }

        return false;
        }
        });
        // menampilkan daftar pesan
        listView.setAdapter(dataAdapter);

        // jika di pesan di klik, maka akan dialihkan ke form_decrypt
        listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView listView, View view, int position, long id) {
        // Get the cursor, positioned to the corresponding row in the result set
        Cursor cursor = (Cursor) listView.getItemAtPosition(position);

        // Get the state’s capital from this row in the database.
        String view_pengirim = cursor.getString(cursor.getColumnIndexOrThrow(“address”));
        String view_isipesan = cursor.getString(cursor.getColumnIndexOrThrow(“body”));

        Intent click = new Intent(list_inbox.this, form_decrypt.class);
        // get contact name
        Uri contactUri = Uri.withAppendedPath(
        ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
        Uri.encode(view_pengirim));
        Cursor cur = getContentResolver().query(contactUri, null, null,
        null, null);
        ContentResolver contect_resolver = getContentResolver();

        int size = cur.getCount();
        if (size > 0 && cur != null) {
        for (int i = 0; i < size; i++) {
        cur.moveToPosition(i);

        String id1 = cur.getString(cur
        .getColumnIndexOrThrow(ContactsContract.Contacts._ID));

        Cursor phoneCur = contect_resolver
        .query(contactUri,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id1 },null);

        if (phoneCur.moveToFirst()) {
        String namaKontak = phoneCur.getString(phoneCur
        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        phoneCur.close();
        click.putExtra("no", namaKontak);
        } else {
        click.putExtra("no", view_pengirim);
        }

        }

        cur.close();
        } else {
        click.putExtra("no", view_pengirim);
        }

        // kirim data ke form decrypt
        click.putExtra("msg", view_isipesan);
        Intent i = getIntent();
        click.putExtra("asal", i.getStringExtra("tipepesan"));
        startActivity(click);
        }
        });
        }
        }

  13. Mas kalo mau ditambahin proses enkripsi pake metode caesar cipher cara nya gimana ??

  14. (columnIndex == 2) buat apa ??

  15. gan, kalo ketika dalam 1 contact dia ada 2 nomor telepon dan waktu kita mau pilih nomor, supaya muncul dulu pilihan nomor2nya itu gimana?
    soalnya saya bikin, dia default nomor ke2 atau nomor terakhir yg kita tambahkan ke kontak itu. mohon bantuannya

  16. gan kalo mau delete pesan langsung di list nya gimana ???

  17. sebelumnya ane terima kasih, udah ane import dan sukses :))
    kalo mau nambahin emoticons gimana ya mas heru? :D
    ane newbie mas, thanks infonya ^_^

    • iya sama2 mas agung.
      kalau mau nambahin emoticon, bisa pake metode auto replace text to image, kalau scriptnya saya belum ada, belum pernah nyobain soalnya. hehe

  18. om mw nanya kalo mw nambahin algoritma pada pesan bsa gak ???

  19. gan,
    untuk penyimpanan sms masuk dan sms keluar itu ke database apa?
    jika simpan database, bagaimana struktur databasenya dan gimana cara melihatnya?

  20. Gan mau tanya, bisa develop aplikasi yang sms untuk Penjualan pulsa all operator ga?

    Kalau bisa hubungi saya segera yah gan

  21. Mas, saya mahasiswa tingkat akhir sedang membuat aplikasi enkryptor-decryptor SMS. Mohon bantuannya untuk share ilmu secara langsung ga mas? Terimakasih sebelumnya.

  22. muncul pesan “Kontak belum dipilih” padahal kontak sudah dipilih ??
    kenapa gan ??

  23. keren gan, work fine :)

  24. mas, jka dalam pembuatan aplikasi SMS dlam menggunakan algoritma sandi hill berbasis android. gmn caranya yahh mas???

    thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s