来自广播接收器的短信接收器

时间:2012-08-12 17:48:53

标签: android

我正在构建一个简单的应用,以便在SMS平台上使用broadcast receiver接收ICS,但根本没有接收短信 ...没有显示Toast

我有3个课程:

  1. MessageActivity:哪个是主类
  2. SimpleSmsRecever:接收sms
  3. 回复:回复
  4. 我的主要文件是:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.message"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk android:minSdkVersion="15" />
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MessageActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    
    
            <receiver android:name=".SmsReceiver" >
                <intent-filter>
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>
        </activity>
        <activity android:name=".Reply" >
        </activity>
    </application>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    

    我接收短信的代码是:

    public class SmsReceiver extends BroadcastReceiver {
    
    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG = "SMSBroadcastReceiver";
    private static String sender, body;
    private static int flag = 0;
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
        MessageActivity mvt = null;
    
        Log.i(TAG, "Intent recieved: " + intent.getAction());
    
        if (intent.getAction() == SMS_RECEIVED) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                final SmsMessage[] messages = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }
    
                if (messages.length > -1) {
                    flag = 1;
                    sender = messages[0].getOriginatingAddress();
                    body = messages[0].getMessageBody();
                    Log.i(TAG,
                            "Message recieved: " +   messages[0].getMessageBody());
                    Toast.makeText(context, messages[0].getMessageBody(),
                            Toast.LENGTH_SHORT).show();
    
                }
            }
        }
    }
    }
    

    请帮忙,我觉得它与ICS有关。谷歌搜索时,我在某处读到了...谢谢。

1 个答案:

答案 0 :(得分:-1)

我不确定此解决方案,但会覆盖onPause和onResume方法。