短信的收发简单Demo

阅读更多
短信的发送:
发送短信相当的简单,只需要几行代码,如下:
参数phoneNumber和MsgStr均是String类型,表示接收方的电话号码和短信内容
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
sms.sendTextMessage(phoneNumber, null, MsgStr, pi, null);



短信的接收:
MainActivity:
package com.amaker.sms;

import android.app.Activity;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends Activity {
    //接收短信的action
	public static final String MY_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	MyReceiver receiver = new MyReceiver();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    
   /**
    * 注册接收短信的广播接收器
    * 这里采用了动态的方式注册,也可以在AndroidManifest.xml里静态注册
    */
    
    @Override
    protected void onResume() {
    	super.onResume();
    	
    	IntentFilter filter = new IntentFilter();
    	filter.addAction(MY_ACTION);
    	registerReceiver(receiver, filter);
    }
    /**
     * 取消接收短信的广播接收器
     */
    @Override
    protected void onPause() {
    	super.onPause();
    	unregisterReceiver(receiver);
    }
}


MyReceiver:
package com.amaker.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		SmsMessage sm;
		Bundle bundle = intent.getExtras();
		Object[] pdus = (Object[]) bundle.get("pdus");
		SmsMessage[] messages = new SmsMessage[pdus.length];
		
		if(bundle!=null){
			for (int i = 0; i < pdus.length; i++) {
				messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
			}
		}
		for(SmsMessage currentMessage:messages){
			sm = currentMessage;
			
			String number = sm.getDisplayOriginatingAddress();
			String content = sm.getDisplayMessageBody();
			
			Toast.makeText(context, number+":"+content, Toast.LENGTH_LONG).show();
		}
	}

}


AndroidManifest.xml


    
    

    
        
            
                
                
            
        

    
    
    
    

你可能感兴趣的:(sms,smsmanager)