完成了来电记录的显示, 再来我们来讨论短信记录的显示, 仿照来电记录的显示.
1. 定义 ListView 的子项显示编排 messager.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="horizontal"
android:paddingBottom="1dip"
android:paddingLeft="10dip"
android:paddingTop="4dip" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ff112b7d"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_phone"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_message"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_time"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
package com.elvis.android.blackcontacts;
/**
* Created by elvis on 11/2/15.
*/
public class Messages {
private String name = "";
private String phone = "";
private String message = "";
private String time = "";
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return this.phone;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
public void setTime(String time) {
this.time = time;
}
public String getTime() {
return this.time;
}
public Messages (String name, String ph, String message, String time){
this.name = name;
this.phone = ph;
this.message = message;
this.time = time;
}
public Messages (){
}
}
3. 定义关联画面的适配器 - MessageAdapter.java
package com.elvis.android.blackcontacts;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by elvis on 11/3/15.
*/
public class MessageAdapter extends BaseAdapter {
private static ArrayList<Messages> searchArrayList;
private LayoutInflater mInflater;
public MessageAdapter(Context context, ArrayList<Messages> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = mInflater.inflate(R.layout.messager, parent, false);
TextView tv_name, tv_phone, tv_message, tv_time;
tv_name = (TextView) row.findViewById(R.id.tv_name);
tv_phone = (TextView) row.findViewById(R.id.tv_phone);
tv_message = (TextView) row.findViewById(R.id.tv_message);
tv_time = (TextView) row.findViewById(R.id.tv_time);
tv_name.setText(searchArrayList.get(position).getName());
tv_phone.setText(searchArrayList.get(position).getPhone());
tv_message.setText(searchArrayList.get(position).getMessage());
tv_time.setText(searchArrayList.get(position).getTime());
return (row);
}
public void updateResults(ArrayList<Messages> results) {
searchArrayList = results;
//Triggers the list update
notifyDataSetChanged();
}
}
4. 短信拦截转存
package com.elvis.android.blackcontacts;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
* Created by elvis on 10/22/15.
*/
public class SmsReceiver extends BroadcastReceiver {
private final String TAG = "SmsReceiver";
private BlackInfoDBHelper dbhelper;
private SharedPreferences sp;
private DevicePolicyManager devicePolicyManager;
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Message Received!!!");
dbhelper = new BlackInfoDBHelper(context);
final Bundle bundle = intent.getExtras();
try {
devicePolicyManager = (DevicePolicyManager)
context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
for(Object pdu:pdus) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdu);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.i(TAG, phoneNumber + ":" + message);
if (dbhelper.isBlackNumber(phoneNumber)) {
Log.i(TAG, "Block!!!");
dbhelper.insertMessage(phoneNumber, message);
//abortBroadcast();
} else {
for (int i = 0; i < 1000; i++)
Toast.makeText(context, phoneNumber + ":" + message,
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Log.e(TAG, "Exception smsReceiver" +e);
}
}
}
5. 资料写入方法及查询方法
/**
* Created by elvis on 10/14/15.
*/
package com.elvis.android.blackcontacts;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Parcelable;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class BlackInfoDBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "econtacts.db";
private final static int DATABASE_VERSION = 1;
private static final String DATABASE_PATH = "/data/data/com.elvis.android.blackcontacts" +
"/databases/";
private static final String TABLE_CONTACT = "contact_info";
private static SQLiteDatabase mDataBase;
private static final String KEY_ID = "serialno";
private static final String KEY_NAME = "name";
private static final String KEY_ALIAS = "alias";
private static final String KEY_PH1 = "phone1";
private static final String KEY_PH2 = "phone2";
private static final String KEY_REMARK = "remark";
private static String TAG = "BlackInfoDBHelper";
private static Context context = null;
private static int MAX_CONTACT_NUMBER = 100;
private int id_mapping[] = new int[MAX_CONTACT_NUMBER];
public BlackInfoDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
try {
//Log.i(TAG, "OK");
this.context = context;
createDataBase();
openDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* TODO Auto-generated method stub */
}
private boolean checkDataBase() {
File dbFile;
dbFile = context.getDatabasePath(DATABASE_NAME);
return dbFile.exists();
}
private void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
// By calling this method an empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
this.close();
try {
copyDataBase();
Log.i(TAG, "Database was created");
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void openDataBase() throws SQLException {
// Open the database
String myPath = DATABASE_PATH + DATABASE_NAME;
Log.i(TAG, "DB_PATH = "+ myPath);
mDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
public void copyDataBase() throws IOException {
// Open your local db as the input stream
//InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DATABASE_NAME);
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public ArrayList<Contacts> select(String query) throws SQLException {
//Cursor c=null;
ArrayList<Contacts> objects = new ArrayList<Contacts>();
Log.i(TAG, "SQL Command = " + query);
Cursor c=null;
try {
c = mDataBase.rawQuery(query, null);
int id[]=new int[c.getCount()];
int i=0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i]=c.getInt(c.getColumnIndex("name"));
id_mapping[i] = c.getInt(0);
Log.i(TAG, "Name: " + c.getString(1));
i++;
Contacts cons = new Contacts(c.getString(1), c.getString(2),
c.getString(3), c.getString(4), c.getString(5));
objects.add(cons);
//cursor = c;
} while (c.moveToNext());
c.close();
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return objects;
}
public ArrayList<Calls> select_calls() throws SQLException {
//Cursor c=null;
ArrayList<Calls> objects = new ArrayList<Calls>();
String cmd = "select * from block_phone";
Log.i(TAG, "SQL Command = " + cmd);
Cursor c=null;
try {
c = mDataBase.rawQuery(cmd, null);
//int id[]=new int[c.getCount()];
int i=0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
//id[i]=c.getInt(c.getColumnIndex("phone"));
//id_mapping[i] = c.getInt(0);
Log.i(TAG, "Name: " + c.getString(1));
//i++;
Calls call = new Calls("", c.getString(1), c.getString(2));
call.setName(queryName(call.getPhone()));
objects.add(call);
//cursor = c;
} while (c.moveToNext());
c.close();
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return objects;
}
public ArrayList<Messages> select_messages() throws SQLException {
//Cursor c=null;
ArrayList<Messages> objects = new ArrayList<Messages>();
String cmd = "select * from block_message";
Log.i(TAG, "SQL Command = " + cmd);
Cursor c=null;
try {
c = mDataBase.rawQuery(cmd, null);
//int id[]=new int[c.getCount()];
int i=0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
//id[i]=c.getInt(c.getColumnIndex("phone"));
//id_mapping[i] = c.getInt(0);
Log.i(TAG, "Name: " + c.getString(1));
//i++;
Messages sms = new Messages("", c.getString(1), c.getString(2), c.getString(3));
sms.setName(queryName(sms.getPhone()));
objects.add(sms);
//cursor = c;
} while (c.moveToNext());
c.close();
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return objects;
}
public boolean isBlackNumber(String number) {
boolean exist = false;
String cmd_query = "select serialno from contact_info where phone1='" +
number + "' or phone2='" + number + "'";
Log.i(TAG, "SQL Command = " + cmd_query);
Cursor c=null;
try {
c = mDataBase.rawQuery(cmd_query, null);
if (c.getCount() > 0)
{
exist = true;
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return exist;
}
public void add(String name, String alias, String phone1, String phone2, String remark) {
String cmd_exec = "insert into contact_info values (NULL, '" + name + "', '" +
alias + "', '" + phone1 + "', '" + phone2 + "', '" + remark + "')";
Log.i(TAG, "SQL Command = " + cmd_exec);
try {
mDataBase.execSQL(cmd_exec);
} catch (Exception e) {
} finally {
}
}
public void update(int no, String name, String alias, String phone1, String phone2, String remark) {
String cmd_exec = "update contact_info set name='" + name + "', alias='" +
alias + "', phone1='" + phone1 + "', phone2='" + phone2 + "', remark='" + remark +
"' where serialno=" + Integer.toString(no);
Log.i(TAG, "SQL Command = " + cmd_exec);
try {
mDataBase.execSQL(cmd_exec);
} catch (Exception e) {
} finally {
}
}
public void delete(int no) {
String cmd_exec = "delete from contact_info where serialno=" + Integer.toString(no);
Log.i(TAG, "SQL Command = " + cmd_exec);
try {
mDataBase.execSQL(cmd_exec);
} catch (Exception e) {
} finally {
}
}
public Contacts query(int no) {
Contacts contact = new Contacts("", "", "", "", "");
String cmd_query = "select name, alias, phone1, phone2, remark from contact_info where " +
"serialno=" + Integer.toString(no);
Log.i(TAG, "SQL Command = " + cmd_query);
Cursor c=null;
try {
c = mDataBase.rawQuery(cmd_query, null);
if (c.getCount() > 0)
{
c.moveToFirst();
do {
contact.setName(c.getString(0));
contact.setAlias(c.getString(1));
contact.setPhone1(c.getString(2));
contact.setPhone2(c.getString(3));
contact.setRemark(c.getString(4));
//cursor = c;
} while (c.moveToNext());
c.close();
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return contact;
}
public int getSelectedSerialNo(int pos) {
return id_mapping[pos];
//return -1;
}
public void insertCaller(String number) {
String cmd_exec = "insert into block_phone values (NULL, '" + number +
"', datetime('now'))";
Log.i(TAG, "SQL Command = " + cmd_exec);
try {
mDataBase.execSQL(cmd_exec);
} catch (Exception e) {
} finally {
}
}
public void insertMessage(String number, String message) {
String cmd_exec = "insert into block_message values (NULL, '" + number + "', '" +
message + "', datetime('now'))";
Log.i(TAG, "SQL Command = " + cmd_exec);
try {
mDataBase.execSQL(cmd_exec);
} catch (Exception e) {
} finally {
}
}
public String queryName(String number) {
String name = "";
String cmd = "select name from contact_info where phone1='" + number + "' or phone2='" +
number + "'";
Cursor c=null;
try {
c = mDataBase.rawQuery(cmd, null);
if (c.getCount() > 0)
{
c.moveToFirst();
do {
name = (c.getString(0));
//cursor = c;
} while (c.moveToNext());
c.close();
}
} catch (Exception e) {
c.close();
} finally {
if(c!=null) {
c.close();
}
}
c.close();
return name;
}
}
6. 关联及显示
package com.elvis.android.blackcontacts;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
import android.content.Intent;
import android.util.Log;
import java.util.ArrayList;
public class ManageBlockInfoActivity extends Activity {
//private BlackInfoDBHelper dbhelper;
private CallAdapter callAdapter;
private MessageAdapter smsAdapter;
private ListView lv_block_phone, lv_block_message;
Context context;
static final String TAG = "ManageBlockInfoActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_block_info);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
Log.i(TAG, "status = " + status);
BlackInfoDBHelper dbhelper = MainActivity.getAdapter();
ArrayList<Calls> calls = dbhelper.select_calls();
//ArrayList<Calls> objects = null;
callAdapter = new CallAdapter(this.getApplicationContext(), calls);
lv_block_phone = (ListView)findViewById(R.id.lv_block_phone);
lv_block_phone.setAdapter(callAdapter);
ArrayList<Messages> messages = dbhelper.select_messages();
smsAdapter = new MessageAdapter(this.getApplicationContext(), messages);
lv_block_message = (ListView)findViewById(R.id.lv_block_message);
lv_block_message.setAdapter(smsAdapter);
}
}
7. 结果展示