每当从某人收到的消息时,广播接收器将读取传入消息并将该消息插入sqlite db。
但是,当调用SmsBroadCastReciever.java
时,在inst.updateList(smsMessageStr);
处使用OnRecieve方法创建CommanDataSource实例。
SmsActivity.java
package com.highcourt.androidreceivesms;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.highcourt.shortcutbadger.ShortcutBadgeException;
import com.highcourt.shortcutbadger.ShortcutBadger;
public class SmsActivity extends Activity implements OnItemClickListener {
private static SmsActivity inst;
private ArrayList<String> smsMessagesList = new ArrayList<String>();
private ListView smsListView;
private ArrayAdapter arrayAdapter;
private CommentsDataSource datasource;
private List<Comment> values;
public static int count = 1;
private ProgressDialog prgDialog;
private Handler mHandler = new Handler();
public static SmsActivity instance() {
return inst;
}
@Override
public void onStart() {
super.onStart();
inst = this;
}
@TargetApi(Build.VERSION_CODES.DONUT)
private void setUpDelete(String smsId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
deleteSms(smsId);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancel(0);
smsListView = (ListView) findViewById(R.id.SMSList);
arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
datasource = new CommentsDataSource(this);
datasource.open();
refreshSmsInbox();
}
public void refreshSmsInbox() {
values = datasource.getAllComments();
for (int i = 0; i < values.size(); i++) {
Comment comment = values.get(i);
arrayAdapter.add(comment);
}
}
public void updateList(final String smsMessage) {
datasource.createComment(smsMessage);
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
// setUpDelete(smsMessage);
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
alertMessage(pos);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void closeDialog(ProgressDialog prgDialog) {
if (prgDialog != null && prgDialog.isShowing()) {
prgDialog.dismiss();
prgDialog = null;
}
}
public boolean deleteSms(String smsId) {
boolean isSmsDeleted = false;
Cursor c = null;
try {
Uri uri = Uri.parse("content://sms");
c = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(c);
// Read the sms data and store it in the list
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
String body = c.getString(c.getColumnIndexOrThrow("body"))
.toString();
String address = c.getString(
c.getColumnIndexOrThrow("address")).toString();
/*
* if (address.equalsIgnoreCase("DD-NICSMS") ||
* address.contains("NICSMS")) {
*/
if (address.equalsIgnoreCase("nicsms")
|| address.contains("WAYSMS")
|| address.equals("TD-bytwoo")
|| address.equals("DZ-HYDPOL")
|| address.equals("IM-bytwoo")) {
int rows = getApplication().getContentResolver()
.delete(Uri.parse("content://sms"),
"address=?", new String[] { address });
isSmsDeleted = true;
}
c.moveToNext();
}
} else {
c.close();
}
} catch (Exception ex) {
if (c != null) {
c.close();
}
isSmsDeleted = false;
Log.d("Could not delete SMS from inbox: " + ex.getMessage(), smsId);
}
return isSmsDeleted;
}
protected void onResume() {
super.onResume();
// count--;
try {
// https://github.com/leolin310148/ShortcutBadger
ShortcutBadger.setBadge(getApplicationContext(), 0);
} catch (ShortcutBadgeException e) {
e.printStackTrace();
}
};
private void progressDialog() {
prgDialog = new ProgressDialog(SmsActivity.this);
prgDialog.setMessage("Deleting...");
prgDialog.show();
}
public void alertMessage(final int position) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
progressDialog();
Comment comment = (Comment) arrayAdapter.getItem(position);
datasource.deleteComment(comment);
arrayAdapter.remove(comment);
arrayAdapter.notifyDataSetChanged();
closeDialog(prgDialog);
Toast.makeText(SmsActivity.this, "Deleted.",
Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
// do nothing and stay with in same screen.
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Confirm Delete?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
}
SmsBroadCastReceiver.java
package com.highcourt.androidreceivesms;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsMessage;
import com.highcourt.shortcutbadger.ShortcutBadgeException;
import com.highcourt.shortcutbadger.ShortcutBadger;
@SuppressWarnings("deprecation")
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
@SuppressLint("NewApi")
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage
.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String phoneNumber = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + phoneNumber + "\n";
smsMessageStr += smsBody + "\n";
/*
* Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT)
* .show();
*/
/*
* if (phoneNumber.equalsIgnoreCase("nicsms") ||
* phoneNumber.contains("WAYSMS") ||
* phoneNumber.equals("TD-bytwoo") ||
* phoneNumber.equals("DZ-HYDPOL") ||
* phoneNumber.equals("IM-bytwoo")) {
*/
/*
* if (phoneNumber.equalsIgnoreCase("DD-NICSMS") ||
* phoneNumber.contains("NICSMS")) {
*/
// works well only upto 4.2.2
this.abortBroadcast();
showNotification(context, smsBody);
try {
ShortcutBadger.setBadge(context, 1);
} catch (ShortcutBadgeException e) {
e.printStackTrace();
}
// BadgeUtils.setBadge(context, SmsActivity.count);
// }
/*
* Format formatter = new SimpleDateFormat("hh:mm:ss a");
* formatter.format(new Date());
*/
// this will update the UI with message
SmsActivity inst = SmsActivity.instance();
// Log.d("SmsActivity:::", inst.toString());
inst.updateList(smsMessageStr);
}
}
}
private void showNotification(Context context, String notificationMessage) {
// Creates an explicit intent for an Activity in your app
Intent notificationIntent = new Intent(context,
com.highcourt.androidreceivesms.SmsActivity.class);
notificationIntent.putExtra("NotificationMessage", notificationMessage);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
// shown TestDatabaseActivity.class when the user is notified
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.stat_notify_chat)
.setContentTitle("SMS Of HighCourt")
.setContentText(notificationMessage)
// Set PendingIntent into Notification
.setContentIntent(contentIntent).setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND);
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
// Check for network availability
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}