android监听短信
16lz
2021-01-23
android中可以通过设置写一个继承自BroadcastReceiver的Receiver来重写接收到短信之后的逻辑处理:
< receiverandroid:name = " .filter.SmsReceiver " >< intent - filter >
< actionandroid:name = " android.provider.Telephony.SMS_RECEIVED " />
</ intent - filter >
</ receiver >
发送短信后的Broadcast:
1 ContentObserver
先写一个观察者:
代码 public class SmsObserverextendsContentObserver{private Contextcontext;
private static finalString[]SMS_PROJECTION = new String[]{
" address " , " person " , " date " , " type " , " body " ,
};
public SmsObserver(Contextcontext,Handlerhandler){
super(handler);
this .context = context;
Log.i( " Leo-SmsObserver " , " MyOberveroncreate " );
}
public void onChange(booleanselfChange){
Log.i( " SmsObserver " , " smsonChange###### " );
}
}
然后在Acitivty或Service里注册这个观察者
getContentResolver().registerContentObserver(Uri.parse( " content://sms " ),true , new SmsObserver( this , new Handler()));
2 可以自定义BroadcastReceiver来实现~
代码 SmsManagersmsManager = SmsManager.getDefault();// TODOAuto-generatedmethodstub
try
{
/* 创建自定义Action常数的Intent(给PendingIntent参数之用) */
IntentitSend = new Intent(SMS_SEND_ACTIOIN);
IntentitDeliver = new Intent(SMS_DELIVERED_ACTION);
/* sentIntent参数为传送后接受的广播信息PendingIntent */
PendingIntentmSendPI = PendingIntent.getBroadcast
(getApplicationContext(), 0 ,itSend, 0 );
/* deliveryIntent参数为送达后接受的广播信息PendingIntent */
PendingIntentmDeliverPI = PendingIntent.getBroadcast
(getApplicationContext(), 0 ,itDeliver, 0 );
/* 发送SMS短信,注意倒数的两个PendingIntent参数 */
smsManager.sendTextMessage
(strDestAddress, null ,strMessage,mSendPI,mDeliverPI);
mTextView01.setText(R. string .str_sms_sending);
}
catch (Exceptione)
{
mTextView01.setText(e.toString());
e.printStackTrace();
} 代码 /* 自定义mServiceReceiver覆盖BroadcastReceiver聆听短信状态信息 */
public class mServiceReceiverextendsBroadcastReceiver
{
@Override
public void onReceive(Contextcontext,Intentintent)
{
// TODOAuto-generatedmethodstub
try
{
/* android.content.BroadcastReceiver.getResultCode()方法 */
switch (getResultCode())
{
case Activity.RESULT_OK:
/* 发送短信成功,这里写需要的代码 */
// mTextView01.setText(R.string.str_sms_sent_success);
mMakeTextToast
(
getResources().getText
(R. string .str_sms_sent_success).toString(),
true
);
break ;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
/* 发送短信失败 */
// mTextView01.setText(R.string.str_sms_sent_failed);
mMakeTextToast
(
getResources().getText
(R. string .str_sms_sent_failed).toString(),
true
);
break ;
case SmsManager.RESULT_ERROR_RADIO_OFF:
break ;
case SmsManager.RESULT_ERROR_NULL_PDU:
break ;
}
}
catch (Exceptione)
{
mTextView01.setText(e.toString());
e.getStackTrace();
}
}
}
更多相关文章
- Android 实例子源代码文件下载地址380个合集
- 安卓布局属性代码中文注解
- Android 4.2启动代码分析(一)
- Android JNI简单实例(android 调用C/C++代码)
- Android 近百个项目的源代码,覆盖Android开发的每个领域
- Android 白板代码实现
- AndroidMenifest.xml(Android清单文件)内部代码分析