2016-08-20 148 views
0

我想開發一個應用程序,以便在收到短信時通知Toast。通過使用BroadcastReceiver下面是我的代碼:使用廣播接收器收到短信時要顯示Toast

public class SMSBroadcastReceiver extends BroadcastReceiver { 

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; 
    private static final String TAG = "SMSBroadcastReceiver"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     Log.e(TAG, "Intent received: " + intent.getAction()); 

     if (intent.getAction().equals(SMS_RECEIVED)) { 

      Toast.makeText(context, "new incoming message" , Toast.LENGTH_LONG).show(); 
     } 

    } 

} 

和清單文件:

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

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <activity 
      android:name=".MainActivity" 
      android:theme="@style/AppTheme"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver android:name=".SMSBroadcastReceiver"> 
      <intent-filter> 
       <action android:name="android.provider.telephony.SMS_RECEIVED"></action> 
      </intent-filter> 
     </receiver> 

    </application> 

問題既不是Log也不Toast被顯示。問題在哪裏,我應該怎麼做?

+0

請在谷歌搜索短信廣播。你會解決它:) –

+0

我已經搜查,但沒有有用的結果。 –

+0

'telephony'需要在清單中的''''中大寫。 ' 「android.provider.Telephony.SMS_RECEIVED」'。另外,如果您在Marshmallow +上運行,請確保您正確處理權限。確保安裝後至少運行一次'MainActivity'。 –

回答

-1

我一直在使用下面的代碼爲我的短信接收器:

<receiver android:name=".SMSBroadcastReceiver" 
       android:permission="android.permission.BROADCAST_SMS"> 
     <intent-filter android:priority="1000"> 
      <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
     </intent-filter> 
    </receiver> 
+0

不幸的是沒有工作 –

0
public class SmsReceiver extends BroadcastReceiver { 

    private String TAG = SmsReceiver.class.getSimpleName(); 

    public SmsReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Get the data (SMS data) bound to intent 


     Bundle bundle = intent.getExtras();  

     if (bundle != null) { 
      // Retrieve the SMS Messages received 
      Object[] pdus = (Object[]) bundle.get("pdus"); 
      SmsMessage msgs = new SmsMessage[pdus.length]; 
      //YOUR TOAST 
     } 
} 

你可以從msgs

並在清單文件

<receiver 
      android:name=".broadcast.SmsReceiver" 
      android:enabled="true" 
      android:exported="true"> 
      <intent-filter android:priority="999"> 
       <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
      </intent-filter> 
</receiver> 

工作文件獲得詳細信息在現場應用程序。 希望這會有所幫助..