【Android】利用广播Broadcast接收SMS短信

BroadcastReceiver

package com.app.test02;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
/**
 * 以BroadcastReceiver接收SMS短信
 * */
public class BroadCastTest2_SMS extends BroadcastReceiver{
	public static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (ACTION.equals(intent.getAction())) {
			Intent i = new Intent(context, BroadCastActivity2_SMS.class);
			i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			SmsMessage[] msgs = getMessageFromIntent(intent);
			
			StringBuilder sBuilder = new StringBuilder();
			if (msgs != null && msgs.length > 0 ) {
				for (SmsMessage msg : msgs) {
					sBuilder.append("接收到了短信:\n发件人是:");
					sBuilder.append(msg.getDisplayOriginatingAddress());
					sBuilder.append("\n------短信内容-------\n");
					sBuilder.append(msg.getDisplayMessageBody());
					i.putExtra("sms_address", msg.getDisplayOriginatingAddress());
					i.putExtra("sms_body", msg.getDisplayMessageBody());
				}
			}
			Toast.makeText(context, sBuilder.toString(), 1000).show();
			context.startActivity(i);
		}
		
	}
	
	public static SmsMessage[] getMessageFromIntent(Intent intent) {
		SmsMessage retmeMessage[] = null;
		Bundle bundle = intent.getExtras();
		Object pdus[] = (Object[]) bundle.get("pdus");
		retmeMessage = new SmsMessage[pdus.length];
		for (int i = 0; i < pdus.length; i++) {
			byte[] bytedata = (byte[]) pdus[i];
			retmeMessage[i]  = SmsMessage.createFromPdu(bytedata);
		}
		return retmeMessage;
	}
}

AndroidManifest注册

        
            
                
            
        

权限

	

Activity文件

package com.app.test02;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class BroadCastActivity2_SMS extends Activity{
	private TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_bc2_sms);
		
		textView = (TextView) findViewById(R.id.textView1);
		Intent intent = getIntent();
		if (intent != null) {
			String address = intent.getStringExtra("sms_address");
			if (address != null) {
				textView.append("\n\n发件人:\n" + address);
				String bodyString = intent.getStringExtra("sms_body");
				if (bodyString != null) {
					textView.append("\n短信内容:\n" + bodyString);
				}
			}
		}
	}
}

Layout布局文件




    

        
  
    



效果图

【Android】利用广播Broadcast接收SMS短信_第1张图片

【Android】利用广播Broadcast接收SMS短信_第2张图片

你可能感兴趣的:(Android,Android组件研究)