![](/img/trans.png)
[英]Send and receive SMS inside my own application only, not in the native Message application in android using native SMS API
[英]Receive only sms of a particular format by my application
我正在使用Brodcast Receiver類通過我的應用程序接收短信。 我還對清單文件中的應用程序賦予了優先權。 我已經在我的應用程序中編寫了代碼,如果短信格式特殊,則應加載第二個屏幕。 當sms為特定格式時,它運行良好,但是當我以任何其他格式發送消息時(由於我的應用程序被賦予了更高的優先級,它將首先接收sms(我的假設),然后生成強制關閉對話框,但消息顯示在通知欄中。
我要的是,如果短信具有特定格式,則應由我的應用程序處理,否則應由系統處理?
我的主要文件是:
package com.example.smsapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SMSApp extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
// str += "SMS from " + msgs[i].getOriginatingAddress();
// str += " :";
str += msgs[i].getMessageBody().toString();
// str += "\n";
}
//---display the new SMS message---
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
String[] msgText;
msgText=str.split(",");
if(msgText[0].equals("second"))
{
Intent i = new Intent(context,Second.class);
i.putExtra("msg",msgText[1]);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
this.abortBroadcast();
}
}
清單文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.smsapp" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="Second" class=".second"
android:label="SMSApp">
</activity>
<receiver android:name=".SMSApp">
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
在您的代碼中,這兩行是元凶
msgText=str.split(",");
if(msgText[0].equals("second"))
無論消息中是否包含逗號,您的代碼都會檢查該逗號,然后在第二行中檢查msgText
數組,如果這不是您期望的msg,則該數組實際上為null ,因此將第二行替換為
if(msgTxt != null && msgText[0].equals("second"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.