大三了,开始学Android 了,做了一个有关通讯的Android应用,我想把其中比较好的内容整理出来,系统的分析一下,这样会学到更多。首先谈到了Android如何管理手机短信,本篇主要讲解下如何管理手机短信,当人主要是我的个人理解。
话不多说首先看图
从图中我们看出了 ,可以显示未读短信的内容,listview(下来刷新)显示短信列表。还有发短信与接收短信的功能。
我们从一个界面一个界面进行讲解(讲解均在代码中),布局文件我就不指出了,最后我会给我的源代码,如果有想要的朋友可以下载
<span style="font-size:18px;">package com.example.androidmessage; import com.example.androidmessage.ui.BadgeView; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.view.Menu; import android.view.View; import android.view.Window; import android.widget.RelativeLayout; public class MainActivity extends Activity { private RelativeLayout messageRelative; SMSQueryHandler smsQuery; BadgeView smsbadge; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); smsbadge = new BadgeView(this, findViewById(R.id.rl_sms)); messageRelative = (RelativeLayout) findViewById(R.id.rl_sms); smsQuery = new SMSQueryHandler(getContentResolver()); messageRelative .setOnClickListener(new RelativeLayout.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(MainActivity.this, MessageActivity.class); startActivity(intent); } }); } // 未读短信 private void showUnreadSMS() { //获得短信的uri ;访问contentprovider 的默认协议是content:// ,sms即代表短信 Uri uri = Uri.parse("content://sms"); String[] projection = new String[] { "count(_id) as count" }; //这句会执行onQueryComplete() smsQuery.startQuery(0, null, uri, projection, "read = 0 ", null, "date asc"); } //为什么要使用AsyncQueryHandler //当然你也可以使用ContentProvider去操作数据库。 // 这在数据量很小的时候是没有问题的,但是如果数据量大了,可能导致UI线程发生ANR事件。 // 当然你也可以写个Handler去做这些操作,只是你每次使用ContentProvider时都要再写个Handler,必然降低了效率。 // 因此API提供了一个操作数据库的通用方法。 private class SMSQueryHandler extends AsyncQueryHandler { public SMSQueryHandler(ContentResolver cr) { super(cr); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { super.onQueryComplete(token, cookie, cursor); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); //获得projection中的第一个数据,即统计了为读短信read=0,的个数 int count = cursor.getInt(0); if (count > 0) { smsbadge.setText(String.valueOf(count)); smsbadge.show(); } else { smsbadge.hide(); } } } } @Override protected void onResume() { super.onResume(); showUnreadSMS(); } } </span>
接下来讲解第二个界面,即获得短信列表。这里会有一个下拉的listview,自定义的控件,下节我会根据本人简单讲解下自定义控件。
<span style="font-size:18px;">package com.example.androidmessage; import java.util.HashMap; import java.util.List; import java.util.Map; import com.example.androidmessage.bean.SMSBean; import com.example.androidmessage.bean.adapter.MessageAdapter; import com.example.androidmessage.ui.RexseeSMS; import com.example.androidmessage.ui.view.RefreshSupportListView; import com.example.androidmessage.ui.view.RefreshSupportListView.OnLoadListener; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; public class MessageActivity extends Activity { private RefreshSupportListView listView; private MessageAdapter adapter; private int pageSize = 20; List<SMSBean> list_mmt; private RexseeSMS rsms; String smsID =""; private boolean flagRefresh=false; int lastItem; private boolean Loading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_message); init(); } private void init() { // TODO Auto-generated method stub setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); listView=(RefreshSupportListView)findViewById(R.id.sms_list); // Sets the drawable that will be drawn between each item in the list. listView.setDivider(this.getResources().getDrawable(R.drawable.cell_seperator)); //异步 new AsyncTask<String, String, String>(){ @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); Log.v("test", "onPreExecute"); } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub Log.v("test", "doInBackground"); adapter = new MessageAdapter(MessageActivity.this); rsms = new RexseeSMS(MessageActivity.this); list_mmt = rsms.getSmsThreads(pageSize); return null; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); Log.v("test", "onPostExecute"); adapter.assignment(list_mmt); listView.setAdapter(adapter); listView.setVisibility(View.VISIBLE); findViewById(R.id.progress).setVisibility(View.GONE); } }.execute(); //下来刷新 listView.setonRefreshListener(new RefreshSupportListView.OnRefreshListener(){ public void onRefresh() { flagRefresh=true; new LoadTask().execute(new String[]{}); } }); //跳转到下一个界面 listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //看信息 Map<String, String> map = new HashMap<String, String>(); SMSBean sb = adapter.getItem(position-1); Bundle bundle=new Bundle(); bundle.putString("phoneNumber", sb.getPhone()); bundle.putString("address", sb.getAddress()); bundle.putString("threadId", sb.getThread_id()); sb.setUnread_count(0); adapter.notifyDataSetChanged(); Intent intent=new Intent(); intent.putExtras(bundle); intent.setClass(MessageActivity.this, MessageBoxList.class); startActivity(intent); // BaseIntentUtil.intentSysDefault(HomeSMSActivity.this, MessageBoxList.class, map); } }); //长按功能 listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub try{ smsID = adapter.getItem(arg2-1).getThread_id(); new AlertDialog.Builder(MessageActivity.this) .setTitle("提示") .setMessage("正在尝试删除当前会话,是否继续?") .setPositiveButton("确 定",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //删除所选中的smsid的哪条短信 Uri mUri=Uri.parse("content://sms/conversations/" + smsID); getContentResolver().delete(mUri, null, null); adapter.assignment(getListResult(list_mmt,smsID)); adapter.notifyDataSetChanged(); } }).setNegativeButton("取 消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //TODO Nothing. } }).create().show(); }catch(Exception e){ e.printStackTrace(); } return false; } }); //加载更多 listView.setonLoadListener(new OnLoadListener() { public void onLoad() { flagRefresh=false; ProgressBar moreProgressBar = (ProgressBar) listView.findViewById(R.id.pull_to_refresh_progress); moreProgressBar.setVisibility(View.VISIBLE); TextView loadMoreView = (TextView) listView.findViewById(R.id.load_more); loadMoreView.setText("正在加载"); new LoadTask().execute(new String[]{}); } }); } private class LoadTask extends AsyncTask<String, Void, List<SMSBean>>{ @Override protected List<SMSBean> doInBackground(String... params) { // List<SMSBean> list_mmt = rsms.getThreadsNum(rsms.getThreads(adapter.getCount()+pageSize)); List<SMSBean> list_mmt = rsms.getSmsThreads(adapter.getCount()+pageSize); return list_mmt; } @Override protected void onPostExecute(List<SMSBean> result) { if (adapter.getCount()==result.size()) { Toast.makeText(MessageActivity.this, "没有更多内容了", Toast.LENGTH_SHORT).show(); } adapter.assignment(result); adapter.notifyDataSetChanged(); listView.setSelection(lastItem-1); Loading = false; super.onPostExecute(result); if(flagRefresh) listView.onRefreshComplete(); else{ listView.onLoadComplete(); TextView loadMoreView = (TextView) listView.findViewById(R.id.load_more); loadMoreView.setText("更多"); } } }; public List<SMSBean> getListResult(List<SMSBean> listBean,String thread_id){ for(int i=0;i<listBean.size();i++){ if(thread_id.equals(listBean.get(i).getThread_id())){ listBean.remove(listBean.get(i)); } } return listBean; } }</span>
<span style="font-size:18px;">我们来看看RexseeSMS,即本节的核心代码</span>
<span style="font-size:18px;"></span><pre name="code" class="html">package com.example.androidmessage.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.example.androidmessage.bean.SMSBean; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.util.Log; import android.widget.RelativeLayout; public class RexseeSMS { public static final String CONTENT_URI_SMS = "content://sms"; public static final String CONTENT_URI_SMS_INBOX = "content://sms/inbox"; public static final String CONTENT_URI_SMS_SENT = "content://sms/sent"; public static final String CONTENT_URI_SMS_CONVERSATIONS = "content://sms/conversations"; public RexseeSMS(Context mContext) { this.mContext=mContext; // TODO Auto-generated constructor stub } public static String[] SMS_COLUMNS = new String[]{ "_id", //0 �?��自增字段,从1�?�� "thread_id", //1 序号,同�?��信人的id相同 "address", //2 发件人手机号�? "person", //3 联系人列表里的序号,陌生人为nul "date", //4 发件日期 "body", //5 短信内容 "read", //6; 0:not read 1:read; default is 0 "type", //7; 0:all 1:inBox 2:sent 3:draft 4:outBox 5:failed 6:queued "service_center" //8 短信服务中心号码编号 }; public static String[] THREAD_COLUMNS = new String[]{ "thread_id", "msg_count", "snippet" }; /** * "_id", "recipient_ids", "message_count", "snippet", "date" "person" */ private static final String[] ALL_THREADS_PROJECTION = new String[]{ "_id", "recipient_ids", "message_count", "snippet", "date", }; /** * "_id", *"address" */ private static final String[] canonical_address = new String[]{ "_id", "address" }; private Context mContext; public String getContentUris() { String rtn = "{"; rtn += "\"sms\":\"" + CONTENT_URI_SMS + "\""; rtn += ",\"inbox\":\"" + CONTENT_URI_SMS_INBOX + "\""; rtn += ",\"sent\":\"" + CONTENT_URI_SMS_SENT + "\""; rtn += ",\"conversations\":\"" + CONTENT_URI_SMS_CONVERSATIONS + "\""; rtn += "}"; return rtn; } public String get(int number) { return getData(null, number); } public String getUnread(int number) { return getData("type=1 AND read=0", number); } public String getRead(int number) { return getData("type=1 AND read=1", number); } public String getInbox(int number) { return getData("type=1", number); } public String getSent(int number) { return getData("type=2", number); } public String getByThread(int thread) { return getData("thread_id=" + thread, 0); } public String getData(String selection, int number) { Cursor cursor = null; ContentResolver contentResolver = mContext.getContentResolver(); try { if (number > 0) { cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS), SMS_COLUMNS, selection, null, "date desc limit " + number); } else { cursor = contentResolver.query(Uri.parse(CONTENT_URI_SMS), SMS_COLUMNS, selection, null, "date desc"); } if (cursor == null || cursor.getCount() == 0) return "[]"; String rtn = ""; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); if (i > 0) rtn += ","; rtn += "{"; rtn += "\"_id\":" + cursor.getString(0); rtn += ",\"thread_id\":" + cursor.getString(1); rtn += ",\"address\":\"" + cursor.getString(2) + "\""; rtn += ",\"person\":\"" + ((cursor.getString(3) == null) ? "" : cursor.getString(3)) + "\""; rtn += ",\"date\":" + cursor.getString(4); rtn += ",\"body\":\"" + cursor.getString(5) + "\""; rtn += ",\"read\":" + ((cursor.getInt(6) == 1) ? "true" : "false"); rtn += ",\"type\":" + cursor.getString(7); rtn += ",\"service_center\":" + cursor.getString(8); rtn += "}"; } return "[" + rtn + "]"; } catch (Exception e) { return "[]"; } } public List<SMSBean> getSmsThreads(int number){ Cursor cursor = null; Cursor cursor_count = null; ContentResolver contentResolver = mContext.getContentResolver(); List<SMSBean> list=new ArrayList<SMSBean>(); List<HashMap> listMap =new ArrayList<HashMap>(); try { //显示会话列表 cursor = contentResolver.query(Uri.parse("content://mms-sms/conversations?simple=true"), ALL_THREADS_PROJECTION, null, null, "date desc limit " + number); if (cursor == null || cursor.getCount() == 0) return list; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); // 游标移动到第i项. SMSBean mmt=new SMSBean(cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getLong(4)); mmt.setAddress(getPersonNamesByThreads(cursor.getString(1), mContext,listMap)); mmt.setPhone(getPersonPhone(cursor.getString(1), mContext)); // Log.v("name tonghu ", "name+"+cursor.getString(5)); //统计是否读取短信 cursor_count = contentResolver.query(Uri.parse("content://sms"), new String[] {"count(_id) as count"}, " thread_id = "+mmt.getThread_id()+" AND read=0 ", null, null); if (cursor_count != null && cursor_count.getCount() > 0) { cursor_count.moveToFirst(); mmt.setUnread_count(cursor_count.getInt(0)); } cursor_count.close(); list.add(mmt); } cursor.close(); return list; } catch (Exception e) { e.printStackTrace(); return list; } } public Long getSmsThreadByPhone(String phone){ Cursor cursor = null; ContentResolver contentResolver = mContext.getContentResolver(); try { cursor = contentResolver.query(Uri.parse("content://mms-sms/canonical-addresses"), canonical_address, " address = '"+ phone+"'", null, null ); try { if (cursor != null) { if (cursor.moveToFirst()) { String _id = cursor.getString(0); Log.v("test id ", "test++++"+_id); cursor = contentResolver.query(Uri.parse("content://mms-sms/conversations?simple=true"), ALL_THREADS_PROJECTION, " recipient_ids = '"+_id+"'", null, null); if (cursor != null) { if (cursor.moveToFirst()) { Log.v("正在测试", String.valueOf(cursor.getLong(0))); return cursor.getLong(0); } } } } } finally { cursor.close(); } }catch (Exception e) { } return null; } public String getPersonNamesByThreads(String recipient_ids, Context mContext,List<HashMap> listMap){ StringBuffer names = new StringBuffer(); Cursor cursor = null; ContentResolver contentResolver = mContext.getContentResolver(); String[] threadid = recipient_ids.split(" "); try { for(String id : threadid){ cursor = contentResolver.query(Uri.parse("content://mms-sms/canonical-addresses"), canonical_address, " _id = "+id , null, null ); if (cursor == null || cursor.getCount() == 0) continue; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); String phoneNum = cursor.getString(1); names.append(","+getPersonNameAll(phoneNum, mContext,listMap)); } cursor.close(); } } catch (Exception e) { e.printStackTrace(); return recipient_ids; } if(names.toString().startsWith(",")){ return names.toString().substring(1, names.toString().length()); }else{ return names.toString(); } } public String getPersonNameAll(String number, Context act,List<HashMap> list) { String name = number; name = name.replaceAll(" ", ""); // for(int i=0;i<list.size();i++){ if(list.get(i).containsKey(number)){ name =list.get(i).get(number).toString(); Log.v("test nmae ", name); break; } } return name; } public String getPersonPhone(String recipient_ids, Context mContext){ StringBuffer names = new StringBuffer(); Cursor cursor = null; ContentResolver contentResolver = mContext.getContentResolver(); String[] threadid = recipient_ids.split(" "); try { for(String id : threadid){ cursor = contentResolver.query(Uri.parse("content://mms-sms/canonical-addresses"), canonical_address, " _id = "+id , null, null ); if (cursor == null || cursor.getCount() == 0) continue; for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); String phoneNum = cursor.getString(1); if (phoneNum.contains("+86")) { phoneNum = phoneNum.substring(3, phoneNum.length()); } names.append(","+phoneNum); } cursor.close(); } } catch (Exception e) { e.printStackTrace(); return recipient_ids; } if(names.toString().startsWith(",")){ return names.toString().substring(1, names.toString().length()); }else{ return names.toString(); } } }
<span style="font-size:18px;"></span><pre name="code" class="html">package com.example.androidmessage; import java.io.UnsupportedEncodingException; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import com.example.androidmessage.bean.MessageBean; import com.example.androidmessage.bean.adapter.MessageBoxListAdapter; import com.example.androidmessage.ui.SmsCodeBroadcast; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.AsyncQueryHandler; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.telephony.SmsManager; import android.text.ClipboardManager; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.LinearLayout.LayoutParams; public class MessageBoxList extends Activity implements OnClickListener { private ProgressDialog pd, firstPd; private String address; private String phone; private String thread; private Button fasong; private EditText neirong; private boolean sendMsg=false;//标识发送短信 private SimpleDateFormat sdf; String SENT_SMS_ACTION = "SENT_SMS_ACTION"; String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED"; PendingIntent sentPI; PendingIntent deliverPI; private List<MessageBean> list = null; private ListView talkView; private MessageBoxListAdapter adapter; SmsCodeBroadcast mReceiver; private AsyncQueryHandler asyncQuery, subAsyncQuery, asyncQueryMMS; private long sendDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_message_box_list); ((ImageView) findViewById(R.id.topbar_ib_1)) .setImageResource(R.drawable.top_return); firstPd = new ProgressDialog(this); firstPd.show(); // 设置短信发送、接收 Intent sentIntent = new Intent(SENT_SMS_ACTION); sentPI = PendingIntent.getBroadcast(MessageBoxList.this, 0, sentIntent, 0); MessageBoxList.this.registerReceiver(sendReceiver, new IntentFilter( SENT_SMS_ACTION)); Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION); deliverPI = PendingIntent.getBroadcast(MessageBoxList.this, 0, deliverIntent, 0); MessageBoxList.this.registerReceiver(receReceiver, new IntentFilter( DELIVERED_SMS_ACTION)); IntentFilter filter = new IntentFilter( "android.provider.Telephony.SMS_RECEIVED"); filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);// 设置优先级最大 mReceiver = new SmsCodeBroadcast(MessageBoxList.this, new SmsCodeBroadcast.AfterReceive() { @Override public void autoFill(String code) { System.out.println("刷新短信界面"); queryAndRefushSms(); initQueryMms(thread); } }, phone); registerReceiver(mReceiver, filter); Button addBtn = new Button(this); addBtn.setBackgroundResource(R.drawable.topbar_bg); addBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addBtn.setGravity(Gravity.CENTER); addBtn.setText("详情"); addBtn.setTextColor(getResources().getColor(R.color.white)); addBtn.setTextSize(15); addBtn.setId(R.id.topbar_ib_2); ((LinearLayout) findViewById(R.id.topbar_linear2)).addView(addBtn); addBtn.setOnClickListener(this); fasong = (Button) findViewById(R.id.fasong); neirong = (EditText) findViewById(R.id.neirong); thread = getIntent().getStringExtra("threadId"); address = getIntent().getStringExtra("address"); phone = getIntent().getStringExtra("phoneNumber"); changeReadToUnread(); TextView tv = (TextView) findViewById(R.id.topbar_tv); tv.setText(address); sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); init(); talkView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub showListDialog(newtan, list.get(arg2)); return true; } }); fasong.setOnClickListener(new OnClickListener() { public void onClick(View v) { sendMsg=true; String content = neirong.getText().toString(); neirong.setText(""); SmsManager smsManager = SmsManager.getDefault(); if (phone.contains(",")) { fasong.setClickable(false); pd = new ProgressDialog(MessageBoxList.this); pd.setCanceledOnTouchOutside(false); pd.setMessage("短信正在发送中..."); pd.show(); String[] phoneArray = new String[] {}; phoneArray = phone.split(","); for (int i = 0; i < phoneArray.length; i++) { if (content.length() >= 70) { // 将短信分成几段 ArrayList<String> ms = smsManager .divideMessage(content); // 发送短信 smsManager.sendMultipartTextMessage(phoneArray[i], null, ms, null, null); } else { smsManager.sendTextMessage(phoneArray[i], null, content, sentPI, deliverPI); } if (i == 0) { ContentValues values = new ContentValues(); values.put("address", phoneArray[i]); values.put("body", content); values.put("thread_id", thread); values.put("date", sendDate); values.put("protocol", "0"); values.put("read", "1"); values.put("status", "-1"); values.put("type", "2"); getContentResolver().insert( Uri.parse("content://sms/sent"), values); } } } else { long date_long = new java.util.Date().getTime(); if (content.length() >= 70) { // 短信字数大于70,自动分条 ArrayList<String> ms = smsManager .divideMessage(content); smsManager.sendMultipartTextMessage(phone, null, ms, null, null); } else { smsManager.sendTextMessage(phone, null, content, sentPI, deliverPI); } // 保存到本地 ContentValues values = new ContentValues(); values.put("address", phone); values.put("body", content); values.put("thread_id", thread); sendDate=new java.util.Date().getTime(); values.put("date", sendDate); values.put("protocol", "0"); values.put("read", "1"); values.put("status", "-1"); values.put("type", "2"); getContentResolver().insert( Uri.parse("content://sms/sent"), values); } } }); } private void init() { // TODO Auto-generated method stub list = new ArrayList<MessageBean>(); asyncQuery = new MyAsyncQueryHandler(getContentResolver()); talkView = (ListView) findViewById(R.id.msg_list); queryAndRefushSms(); initQueryMms(thread); } BroadcastReceiver sendReceiver = new BroadcastReceiver() { @Override public void onReceive(Context _context, Intent _intent) { sendMsg=false; queryAndRefushSms(); initQueryMms(thread); } }; BroadcastReceiver receReceiver = new BroadcastReceiver() { public void onReceive(Context _context, Intent _intent) { switch (getResultCode()) { case Activity.RESULT_OK: try { pd.dismiss(); } catch (Exception e) { // TODO: handle exception } fasong.setClickable(true); // Toast.makeText(MessageBoxList.this, "短信发送成功", Toast.LENGTH_SHORT).show(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: break; case SmsManager.RESULT_ERROR_RADIO_OFF: break; case SmsManager.RESULT_ERROR_NULL_PDU: break; } } }; private void initQueryMms(String thread) { System.out.println("thread=====================++" + thread); asyncQueryMMS = new AsyncQueryMMSHandler(getContentResolver()); Uri uri = Uri.parse("content://mms"); asyncQueryMMS.startQuery(0, null, uri, new String[] { "_id", "date", "msg_box", "sub" }, "thread_id = " + thread, null, null); } /** * 数据库异步查询类AsyncQueryHandler * * @author administrator * */ private class MyAsyncQueryHandler extends AsyncQueryHandler { public MyAsyncQueryHandler(ContentResolver cr) { super(cr); } protected void onQueryComplete(int token, Object cookie, Cursor cursor) { list.clear(); if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); String date = sdf.format(new Date(cursor.getLong(cursor .getColumnIndex("date")))); // type:1 表示过得的短信 其他(2)表示自己发送的短信 if (cursor.getInt(cursor.getColumnIndex("type")) == 1) { MessageBean d = new MessageBean( cursor.getString(cursor .getColumnIndex("address")), date, cursor.getString(cursor.getColumnIndex("body")), R.layout.information_sms_in_msg, cursor .getInt(cursor.getColumnIndex("_id")), "0", cursor.getLong(cursor .getColumnIndex("date")),false); list.add(d); } else { boolean falgSend=false; if(sendMsg){//取刚刚发送的一条短信,将短信发送 if(cursor.getLong(cursor .getColumnIndex("date"))==sendDate){ falgSend=true; } } MessageBean d = new MessageBean( cursor.getString(cursor .getColumnIndex("address")), date, cursor.getString(cursor.getColumnIndex("body")), R.layout.information_sms_out_msg, cursor .getInt(cursor.getColumnIndex("_id")), "0", cursor.getLong(cursor .getColumnIndex("date")),falgSend); list.add(d); } } cursor.close(); } } } private class AsyncQueryMMSHandler extends AsyncQueryHandler { public AsyncQueryMMSHandler(ContentResolver cr) { super(cr); // TODO Auto-generated constructor stub } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { // TODO Auto-generated method stub if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { Log.v("这句已经执行了", "这句已经执行了"); cursor.moveToPosition(i); MessageBean mb = new MessageBean(); String date = sdf.format(new Date((long) cursor .getInt(cursor.getColumnIndex("date")) * 1000)); String _id = cursor.getInt(cursor.getColumnIndex("_id")) + ""; String sub = cursor.getString(cursor.getColumnIndex("sub")); try { if (sub != null) { sub = new String(sub.getBytes("iso-8859-1"), "utf-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } int msg_box = cursor.getInt(cursor .getColumnIndex("msg_box")); Log.v("msg_box++++", "msgBost" + String.valueOf(msg_box)); if (msg_box == 1) { mb.setLayoutID(R.layout.information_sms_in_msg); } else { mb.setLayoutID(R.layout.information_sms_out_msg); } String text = ""; String bitmap_id = ""; mb.set_id(cursor.getInt(cursor.getColumnIndex("_id"))); mb.setDate(date); mb.setSub(sub); // mb.setSub(new String(sub.getBytes(""), "utf-8")); Cursor cur = getContentResolver().query( Uri.parse("content://mms/part"), null, "mid = " + _id, null, null); if (cur.getCount() > 0 && cur != null) { cur.moveToFirst(); for (int j = 0; j < cur.getCount(); j++) { cur.moveToPosition(j); String ct = cur.getString(cur.getColumnIndex("ct")); if ("text/plain".equals(ct)) { text = text + cur.getString(cur .getColumnIndex("text")) + " "; Log.v("test====", "test +++" + text); } else if ("image/jpeg".equals(ct) || "image/jpg".equals(ct) || "image/png".equals(ct) || "image/bmp".equals(ct) || "image/gif".equals(ct)) { bitmap_id = bitmap_id + cur.getInt(cur.getColumnIndex("_id")) + ","; } else if ("audio/mpeg".equals(ct)) { } } cur.close(); mb.setType("1"); mb.setText(text); mb.setBitmap_id(bitmap_id); mb.setDate_long((long) cursor.getInt(cursor .getColumnIndex("date")) * 1000); list.add(mb); } } } if (list.size() > 0) { System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); adapter = new MessageBoxListAdapter(MessageBoxList.this, sort(list)); talkView.setAdapter(adapter); talkView.setDivider(null); talkView.setSelection(list.size()); } else { Toast.makeText(MessageBoxList.this, "没有短信进行操作", Toast.LENGTH_SHORT).show(); } try { firstPd.dismiss(); } catch (Exception e) { // TODO: handle exception } } } private void queryAndRefushSms() { Uri uri = Uri.parse("content://sms"); String[] projection = new String[] { "date", "address", "person", "body", "type", "_id" };// 查询的列 asyncQuery.startQuery(0, null, uri, projection, "thread_id = " + thread, null, "date asc"); } public static List<MessageBean> sort(List<MessageBean> list) { for (int i = 1; i < list.size(); i++) { for (int j = i; j > 0; j--) { if (list.get(j).getDate_long() < list.get(j - 1).getDate_long()) { MessageBean bean = list.get(j - 1); list.set(j - 1, list.get(j)); list.set(j, bean); } else break; } } return list; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } private void changeReadToUnread() { ContentResolver contentResolver = MessageBoxList.this .getContentResolver(); try { // This class is used to store a set of values that the // ContentResolver can process. ContentValues cv = new ContentValues(); cv.put("read", "1"); contentResolver .update(Uri.parse("content://sms"), cv, "thread_id = ? AND read = ? ", new String[] { thread, "0" }); } catch (Exception e) { e.printStackTrace(); } } private String[] newtan = new String[] { "转发", "复制文本内容", "删除" }; private void showListDialog(final String[] arg, final MessageBean mb) { new AlertDialog.Builder(MessageBoxList.this).setTitle("信息选项") .setItems(arg, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // Intent messageIntent = new Intent(ctx, // NewSMSActivity.class); // messageIntent.putExtra("body", mb.getText()); // ctx.startActivity(messageIntent); break; case 1: ClipboardManager cmb = (ClipboardManager) MessageBoxList.this .getSystemService(MessageBoxList.this.CLIPBOARD_SERVICE); cmb.setText(mb.getText()); break; case 2: if ("0".equals(mb.getType())) { Uri mUri = Uri.parse("content://sms/" + mb.get_id()); MessageBoxList.this.getContentResolver().delete(mUri, null, null); } else if ("1".equals(mb.getType())) { Uri mmsUri = Uri.parse("content://mms/" + mb.get_id()); MessageBoxList.this.getContentResolver().delete(mmsUri, null, null); } break; // case 3: // // break; } ; } }).show(); } @Override protected void onDestroy() { MessageBoxList.this.unregisterReceiver(sendReceiver); MessageBoxList.this.unregisterReceiver(receReceiver); // ctx.unregisterReceiver(refushReceiver); MessageBoxList.this.unregisterReceiver(mReceiver); super.onDestroy(); } }
突然发现如果把代码翻译一遍也没有什么好讲的。安卓开发手机管理短信
这个程序我已经运行成功,如果想详细了解下contentProvider可以参考下
http://www.cnblogs.com/kakafra/archive/2012/09/28/2707790.html
接下来就是我的源码了
http://download.csdn.net/detail/u010399009/8498995