2016-08-20 124 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> 

工作文件获得详细信息在现场应用程序。 希望这会有所帮助..