0

现在我将使用 smsReceiver 类。尽管该应用程序在模拟器中运行顺畅,但在真实设备上却显示错误。该应用程序可以安装在两者中,但是当在真实设备下时,它会显示一条消息,例如“SMS LISTENER IS ALREADY UN-REGISTERED”

这是我的 SMSReceiver 类:

  public void onReceive(Context context, Intent intent) {
this.mcontext = context;
if (intent.getAction().equals(VoiceofText.ACTION)) {
    Bundle bundle = intent.getExtras();
if (bundle != null) {
 readSMS(bundle);
}
 }
}

public void readSMS(Bundle bundle) {
SmsMessage[] msgs = null;

try {

 Object[] pdus = (Object[]) bundle.get("pdus");

 if (pdus != null) {

   msgs = new SmsMessage[pdus.length];

   String smsBodyStr = null;
   String phoneNoStr = null;

   for (int k = 0; k < msgs.length; k++) {
    msgs[k] = SmsMessage.createFromPdu((byte[]) pdus[k]);

    smsBodyStr = msgs[k].getMessageBody().trim();

    phoneNoStr = msgs[k].getOriginatingAddress().trim();

    speakSMS(smsBodyStr, phoneNoStr);
      }
}
} catch (Exception exe) {
    exe.printStackTrace();
}
} 

这是我使用的清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="a.b.c"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="8" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

     <receiver android:name=".SmsReceiver">  
         </receiver>      

    <activity
        android:label="@string/app_name"
        android:name=".SMSText" >

                    <intent-filter >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>


 </application>

<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

   </manifest>

在这里,我在名为 SMSText.java 的下一个类中指定 Toast 消息

public void registerSMS() {
receiver = new SMSReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION);
registerReceiver(receiver, filter);

Toast.makeText(getApplicationContext(), "registered for incomming sms",
            Toast.LENGTH_LONG).show();
}


public void unregisterSMS() {
try {
unregisterReceiver(receiver);
Toast.makeText(getApplicationContext(),"unregistered for listening sms",  
                 Toast.LENGTH_LONG).show();
} 
catch (Exception exe) {Toast.makeText(getApplicationContext(),
                "sms listener is already unregistered",  
                        Toast.LENGTH_LONG).show();
 }
}
4

0 回答 0