android 短信

package scl.sms_01;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TestRWSMSActivity extends Activity {
	TextView textReadSMS;
	EditText editReplySMSBody;
	Button buttonReplySMS;
	String address;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.read_reply_sms);

		showSMS();
	}

	private void showSMS() {
		textReadSMS = (TextView) findViewById(R.id.read_sms);
		editReplySMSBody = (EditText) findViewById(R.id.re_body);
		buttonReplySMS = (Button) findViewById(R.id.re_send_button);
		
		String strSMS = null;
		Bundle bundle = getIntent().getExtras();
		address = bundle.getString("address");
		strSMS = "内容:"
				+ bundle.getString("body") + "\n"
				+"时间:"
				+ bundle.getString("date");
		textReadSMS.setText(strSMS);
		int int_read = bundle.getInt("read");
		buttonReplySMS.setOnClickListener(new ButtonReplySMSOnClickListent());
		if(int_read == 0){
		Uri uri = Uri.parse(TestSMSActivity.SMS_URI_INBOX);
		Cursor cursor = managedQuery(uri, null, "address=? and read=? ", new String[]{this.address,"0"}, null);
		if(cursor != null ){
			ContentValues cValue = new ContentValues();
			cValue.put("read", 1);
			cursor.moveToFirst();
			getContentResolver().update(uri, cValue, null, null);
		}
		cursor.close();
		}
	}
	class ButtonReplySMSOnClickListent implements View.OnClickListener{

		public void onClick(View v) {
			String message = editReplySMSBody.getText().toString();
			if(message.length() >0){
				ReSMS(address,message);
				Toast.makeText(getApplicationContext(),R.string.send_success, Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(getApplicationContext(),R.string.send_fail, Toast.LENGTH_LONG).show();
			}
		}

		private void ReSMS(String address, String message) {
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(address, null, message, null, null);
			editReplySMSBody.setText("");
		}
		
	}
}

package scl.sms_01;

public class SMSInfo {
	
	String str_id;//短信序号
	String str_thread_id;//对话序号
	String str_address;//发信人
	String str_date;//日期
	int int_read;//是否阅读 0未读, 1已读
	int int_status;//状态 -1接收,0 complete, 64 pending, 128  failed
	int int_type;//类型 1是接收到的,2是已发出
	String str_body;// 短消息内容
	String str_service_center;//短信服务中心号码编号
	String str_contacts_name;//联系人
	public SMSInfo() {
		
	}
	public SMSInfo(String str_id, String str_thread_id, String str_address,
			String str_date, int int_read, String str_body, int int_status,
			int int_type, String str_service_center,String str_contacts_name) {
		super();
		this.str_id = str_id;
		this.str_thread_id = str_thread_id;
		this.str_address = str_address;
		this.str_date = str_date;
		this.int_read = int_read;
		this.str_body = str_body;
		this.int_status = int_status;
		this.int_type = int_type;
		this.str_service_center = str_service_center;
		this.str_contacts_name = str_contacts_name;
	}
	public String getStr_id() {
		return str_id;
	}
	public void setStr_id(String str_id) {
		this.str_id = str_id;
	}
	public String getStr_thread_id() {
		return str_thread_id;
	}
	public void setStr_thread_id(String str_thread_id) {
		this.str_thread_id = str_thread_id;
	}
	public String getStr_address() {
		return str_address;
	}
	public void setStr_address(String str_address) {
		this.str_address = str_address;
	}
	public String getStr_date() {
		return str_date;
	}
	public void setStr_date(String str_date) {
		this.str_date = str_date;
	}
	public int getInt_read() {
		return int_read;
	}
	public void setInt_read(int int_read) {
		this.int_read = int_read;
	}
	public int getInt_status() {
		return int_status;
	}
	public void setInt_status(int int_status) {
		this.int_status = int_status;
	}
	public int getInt_type() {
		return int_type;
	}
	public void setInt_type(int int_type) {
		this.int_type = int_type;
	}
	public String getStr_body() {
		return str_body;
	}
	public void setStr_body(String str_body) {
		this.str_body = str_body;
	}
	public String getStr_service_center() {
		return str_service_center;
	}
	public void setStr_service_center(String str_service_center) {
		this.str_service_center = str_service_center;
	}
	public String getStr_contacts_name() {
		return str_contacts_name;
	}
	public void setStr_contacts_name(String str_contacts_name) {
		this.str_contacts_name = str_contacts_name;
	}
	
}

package scl.sms_01;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NewSMSActivity extends Activity {
	EditText editphoneNo;
	EditText editcontent;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_sms);
		editphoneNo = (EditText) findViewById(R.id.edt_address);
		editcontent = (EditText) findViewById(R.id.edt_content);
		Button btnSend = (Button) findViewById(R.id.btn_send_new_sms);
		btnSend.setOnClickListener(new View.OnClickListener(){

			public void onClick(View v) {
				String strphone = editphoneNo.getText().toString();
				String strcontent = editcontent.getText().toString();
				if (strphone.length() > 0 && strcontent.length() > 0){
                    sendSMS(strphone, strcontent);
            }
            else{
                    Toast.makeText(getBaseContext(),
                            "号码或短信不能为空",
                            Toast.LENGTH_SHORT).show();
            	}
			}
			private void sendSMS(String strphone, String strcontent) {
				Intent intent = new Intent(NewSMSActivity.this,TestSMSActivity.class);
				PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,intent , 0);
				SmsManager sms = SmsManager.getDefault();
		        
		        if (strcontent.length() > 70) {
		                ArrayList<String> msgs = sms.divideMessage(strcontent);
		                for (String msg : msgs) {
		                        sms.sendTextMessage(strphone, null, msg, pi, null);
		                }
		        } else {
		                sms.sendTextMessage(strphone, null, strcontent, pi, null);
		        }
		        Toast.makeText(NewSMSActivity.this, "已发送", Toast.LENGTH_SHORT).show();
		       /* editphoneNo.setText("");
		        editcontent.setText("");*/
//		        Intent intent = new Intent(NewSMSActivity.this,TestSMSActivity.class);
//		        startActivity(intent);
			}
		});
	}

}

package scl.sms_01;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsMessage;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class TestSMSActivity extends Activity {
	/** Called when the activity is first created. */
	final  String SMS_URI_ALL = "content://sms"; // 所有短信
	final static String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
	final String STR_STRANFE = "陌生人";
	final int MENU_SAVE = Menu.FIRST;
	final int MENU_DELETE = Menu.FIRST+1;
	
	final String _ID = "_id";//短信序号
	final String THREAD_ID = "thread_id";//对话序号
	final String ADDRESS = "address";//发信人
	final String DATE = "date"; //日期
	final String READ = "read"; //是否阅读 0未读, 1已读
	final String STATUS = "status";//状态 -1接收,0 complete, 64 pending, 128  failed 
	final String TYPE = "type"; //类型 1是接收到的,2是已发出
	final String BODY = "body"; // 短消息内容
	final String SERVICE_CENTER = "service_center"; //短信服务中心号码编号
	final String PDUS = "pdus";
	
	ListView listViewSMS = null;
	List<SMSInfo> listSMSInfo = null;
	AdapterListViewSMS adapterListViewSMS = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listViewSMS = (ListView) findViewById(R.id.listview_sms);
		
		TextView textNewSMS = (TextView) findViewById(R.id.new_sms);
//		textNewSMS.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//文字加下划线
		textNewSMS.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Intent intent = new Intent(TestSMSActivity.this,NewSMSActivity.class);
				startActivity(intent);
			}
			
		});
		listSMSInfo = getSMSInfo();
		adapterListViewSMS = new AdapterListViewSMS(this);
		listViewSMS.setAdapter(adapterListViewSMS);
		listViewSMS.setOnItemClickListener(new ListItemClickListener());
		
	}

	private List<SMSInfo> getSMSInfo() {
	/*	从系统短信数据库读取短信*/
		List<SMSInfo> list = new ArrayList<SMSInfo>();
		// list.clear();
		Uri uri = Uri.parse(SMS_URI_ALL);
		
		String[] projection = new String[] { _ID, THREAD_ID, ADDRESS,
				DATE, READ,STATUS, TYPE, BODY, SERVICE_CENTER };
		
		Cursor cursor = getContentResolver().query(uri, projection, null, null,
				"date desc");
		for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
			
			SMSInfo sinfo = new SMSInfo();
			sinfo.str_id = cursor.getString(cursor.getColumnIndex(_ID));
			sinfo.str_thread_id = cursor.getString(cursor.getColumnIndex(THREAD_ID));
			sinfo.str_address = cursor.getString(cursor
					.getColumnIndex(ADDRESS));
			sinfo.str_date = getSimpleDateFormat(cursor.getLong(cursor
					.getColumnIndex(DATE)));
			sinfo.int_read = cursor.getInt(cursor.getColumnIndex(READ));
			sinfo.int_status = cursor.getInt(cursor.getColumnIndex(STATUS));
			sinfo.int_type = cursor.getInt(cursor.getColumnIndex(TYPE));
			sinfo.str_body = cursor.getString(cursor.getColumnIndex(BODY));
			sinfo.str_contacts_name = getContactsNameFromSMSAddress(sinfo.str_address);
			list.add(sinfo);
		}
		closeCursor(cursor);
		return list;
	}
	private void closeCursor(Cursor cursor){
		/*关闭光标*/
		if(!(cursor.isClosed())){
			cursor.close();
			cursor = null;
			}
	}
	private String getSimpleDateFormat(long long_date) {
		/*时间格式转换为"yyyy-MM-dd HH:mm:ss"*/
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date d = new Date(long_date);
		String date = dateFormat.format(d);
		return date;
	}

	private String getContactsNameFromSMSAddress(String str_address) {
		/* 通过address手机号关联Contacts联系人的显示名字 */
		String strPerson = str_address;
		String[] projection = new String[] { Phone.NUMBER, Phone.DISPLAY_NAME };
		/* 过滤手机号码str_address */
		Uri uri_name = Uri.withAppendedPath(
				ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI,
				str_address);
		Cursor cursor = getContentResolver().query(uri_name, projection, null, null, null);
		if(cursor.moveToFirst()){
			strPerson = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
		}
		/*if((strPerson == null) || ("".equals(strPerson))){
			strPerson = STR_STRANFE;
		}*/
		closeCursor(cursor);
		return strPerson;
	}

	private class AdapterListViewSMS extends BaseAdapter{
		private LayoutInflater layoutInflater;
		public AdapterListViewSMS(Context context) {
			layoutInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return listSMSInfo.size();
		}

		public Object getItem(int position) {
			return listSMSInfo.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if(convertView == null){
				convertView = layoutInflater.inflate(R.layout.listview_sms, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}
			else{
				holder = (ViewHolder) convertView.getTag();
			}
			SMSInfo smsInfo = listSMSInfo.get(position);
			
			holder.address.setText(smsInfo.str_contacts_name);
			holder.date.setText(smsInfo.str_date);
			holder.body.setText("说:"+smsInfo.str_body);
			if(smsInfo.int_read == 0){
				holder.address.setTextColor(Color.YELLOW);
				holder.body.setTextColor(Color.YELLOW);
			}else {
				holder.address.setTextColor(Color.GRAY);
				holder.body.setTextColor(Color.GRAY);
			}
			
			return convertView;
		}
		
		class ViewHolder{
			TextView  address;
			TextView date;
			TextView body;
			
			public ViewHolder(View view){
				this.address =(TextView) view.findViewById(R.id.address);	
				this.date = (TextView) view.findViewById(R.id.date);
				this.body = (TextView) view.findViewById(R.id.body);
			}
		}
	}

	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		if((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY){
			Toast.makeText(getApplicationContext(),R.string.welcome, Toast.LENGTH_SHORT).show();
		}
		else {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Toast.makeText(getApplicationContext(),R.string.has_sms, Toast.LENGTH_SHORT).show();
				SMSInfo sinfo = new SMSInfo();
				Object[] pdu = (Object[]) bundle.get(PDUS);
				SmsMessage[] msg = new SmsMessage[pdu.length];
				for (int i = 0; i < pdu.length; i++) {
					msg[i] = SmsMessage.createFromPdu((byte[]) pdu[i]);
				}
				for (SmsMessage currMsg : msg){
					sinfo.str_address = currMsg.getDisplayOriginatingAddress();
					sinfo.str_body = currMsg.getDisplayMessageBody();
					sinfo.str_date = getSimpleDateFormat(currMsg.getTimestampMillis());
					sinfo.str_contacts_name = getContactsNameFromSMSAddress(sinfo.str_address);
				}
				listSMSInfo.add(0,sinfo);
				adapterListViewSMS.notifyDataSetChanged();
			}
		}
	}
	
	class ListItemClickListener implements OnItemClickListener{

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			SMSInfo smsInfo = (SMSInfo) listViewSMS.getItemAtPosition(position); 
//		Toast.makeText(getApplicationContext(), pn, Toast.LENGTH_SHORT).show();
			
			Intent intent = new Intent(TestSMSActivity.this,TestRWSMSActivity.class);
			Bundle extras = new Bundle();
			extras.putString("address", smsInfo.getStr_address());
			extras.putString("body", smsInfo.getStr_body());
			extras.putInt("read", smsInfo.getInt_read());
			extras.putString("date", smsInfo.getStr_date());
			intent.putExtras(extras);
			startActivity(intent);
		}
	}
	@Override
	protected void onRestart() {
		super.onRestart();
		System.out.println("restart");
		listSMSInfo.clear();
		listSMSInfo = getSMSInfo();
		adapterListViewSMS.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		return super.onCreateOptionsMenu(menu);
		menu.add(0,MENU_SAVE,0,"新建").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0,MENU_DELETE, 0, "删除").setIcon(android.R.drawable.ic_menu_delete);
		return true;
	}
}

package scl.sms_01;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class SMSReceiver extends BroadcastReceiver {
	private static String STRACT ="android.provider.Telephony.SMS_RECEIVED";
	Intent intent = null;
	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent.getAction().equals(STRACT)){
			Bundle bundle = intent.getExtras();
			this.intent = new Intent(context,TestSMSActivity.class);
			this.intent.putExtras(bundle);
			this.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			context.startActivity(this.intent);
		}
	}

}

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="scl.sms_01"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-sdk android:minSdkVersion="6"></uses-sdk>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TestSMSActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask"
                  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
		<receiver android:name =".SMSReceiver">
		<intent-filter>
			<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
		</intent-filter>
		</receiver>
		<activity android:name=".TestRWSMSActivity"
				android:windowSoftInputMode="adjustResize"
		/>
		<activity android:name=".NewSMSActivity"/>
    </application>
    <uses-permission android:name="android.permission.READ_SMS"/>
    <uses-permission android:name="android.permission.WRITE_SMS"/>
	<uses-permission android:name="android.permission.SEND_SMS" />
	<uses-permission android:name="android.permission.READ_CONTACTS" />
	<uses-permission android:name="android.permission.RECEIVE_SMS" />
</manifest> 

<?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"
  >
  <TextView
  android:id="@+id/address"
  android:textSize="20dip"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  />
  <TextView
  android:id="@+id/date"
  android:textSize="15dip"
  android:textColor="@drawable/date_color"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentRight="true"
  />
  <TextView
  android:id="@+id/body"
  android:textSize="20dip"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_below="@id/address"
  android:singleLine="true"
  />
  
</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
	android:id="@+id/new_sms"
	android:gravity="center_vertical"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center"
    android:text="@string/newsms"
    android:textSize="20dip"
    />
  
    <ListView
    android:id="@+id/listview_sms"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5.0dip"
    />
</LinearLayout>

<?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">
  <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/txtPhoneNo"/>
            
  <EditText android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:phoneNumber="true"
            android:id="@+id/edt_address"/>
         
    <TextView android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="@string/txtContent"/>
     
    <EditText android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:minLines="3"
              android:id="@+id/edt_content"/>
    
    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/send_button"
            android:id="@+id/btn_send_new_sms"/>
</LinearLayout>

<?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"
  android:layout_marginTop="10dip"
  >
  <TextView
  android:id="@+id/read_sms"
  android:textSize="20dip"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_weight="1"
  />
  <LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:gravity="bottom"
  android:layout_gravity="bottom"
  >
  <Button
  android:id="@+id/re_send_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="1" 
  android:text="@string/send_button"
  android:gravity="center"
  />
  <EditText
  android:id="@+id/re_body"
  android:layout_toRightOf="@id/re_send_button"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:maxLines="3"
  android:layout_weight="7"
  />
  </LinearLayout>
</LinearLayout>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值