//清单文件
<receiver android:name=".Receiver">
<intent-filter android:priority="1000">
<action android:name="com.servicedemo4"/>
</intent-filter>
</receiver>
//mianactivty中
Intent intent = new Intent();
intent.setAction("com.servicedemo4");
//同步广播
Context.sendBroadcast(intent);
//有序广播
Context.sendOrderedBroadcast(intent,null);
//创建一个类用来接收广播(继承BroadcastReceiver)
class SmsListenerReceiver extends BroadcastReceiver {
//在onReceive方法中写接收到广播后要执行的代码
public void onReceive
//下面是接收短信广播
清单文件
权限
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
注册receiver
<receiver android:name=".SmsListenerReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter>
public class SmsListenerReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
Object[] objects=(Object[])intent.getExtras().get("pdus");
for (Object put:objects)
{////
//android.provider.Telephoney
创建一个短信管理对象SmsMessage
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pud);
//获取短信内容
String body = smsMessage.getDisplayMessageBody();
//获取发送人短信号码
String address = smsMessage.getOriginatingAddress();
//获取短信时间
Date date = new Date(smsMessage.getTimestampMillis());//时间
//把获取到的时间戳转化成时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String receiveTime = format.format(date);
Log.e("短信:",address+":"+body+ receiveTime);
}
}
}
网友评论