onReceive永远不会被调用

时间:2011-01-31 18:43:52

标签: java android sms

下面是我的Java代码和我的XML代码。有人可以告诉我为什么我的onReceieve方法永远不会被调用。

爪哇:

public class PopUPSMS extends Activity {

    String RECEIVE_SMS = "RECEIVE_SMS";

    private static final String LOG_TAG = "PopUPSMS";

    static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.i(LOG_TAG, "onCreate");

        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(LOG_TAG, "onReceive");
            }
        }, new IntentFilter(RECEIVE_SMS));
    }
}

XML:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.smith.johnathan.phone"
    android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".PopUPSMS"
            android:label="@string/app_name">
            <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-sdk android:minSdkVersion="3" />
</manifest> 

3 个答案:

答案 0 :(得分:2)

 registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(LOG_TAG, "onReceive");
        }
    }, new IntentFilter(RECEIVE_SMS));

您已使用字符串“RECEIVE_SMS”注册了广播接收器。 IntentFilter应该是一种动作形式。声明:

static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

你将拥有:

registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(LOG_TAG, "onReceive");
            }
        }, new IntentFilter(ACTION));

您可以查看XML声明的Api demos Manifest

答案 1 :(得分:0)

您不能将接收器用作内部类。创建一个单独的。

答案 2 :(得分:0)

您是否需要指定要在清单中接收短信?

<application android:icon="@drawable/icon" android:label="@string/app_name">

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

</application>
相关问题