主要利用BroadcastReceive获得接收来自短信的广播。另外需要获得接收短信的权限。
本例主要是静态使用broadcastReceiver。
MainActivity
package com.example.a_wuyafeng;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main) ;
}
}
MyReceiver
package com.example.a_wuyafeng;
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 {
public void onReceive(Context context, Intent intent) {
// TODO 自动生成的方法存根
System.out.println("myReceiver.java");
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
StringBuilder sb = new StringBuilder() ;
Bundle bundle = intent.getExtras() ;
if(bundle != null){
Object[] obj = (Object[])bundle.get("pdus") ;
SmsMessage[] sm = new SmsMessage[obj.length] ;
int length = obj.length ;
for(int i=0;i<length;i++){
sm[i] = SmsMessage.createFromPdu((byte[])obj[i]) ;
}
for(int i =0 ;i<length;i++){
sb.append("from:\n");
sb.append(sm[i].getDisplayOriginatingAddress()) ;
sb.append("\n") ;
sb.append("content:\n") ;
sb.append(sm[i].getMessageBody()) ;
}
Toast.makeText(context, sb.toString().trim(), Toast.LENGTH_SHORT).show() ;
Intent tempIntent = new Intent(context,MainActivity.class) ;
tempIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
context.startActivity(tempIntent) ;
}
}
}
}
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
</LinearLayout>