2

我已经搜索和搜索,并尝试了我能想到的一切 5 次。我无法让我的广播接收器注册。

目前,在清单中,在应用程序元素中,我有:

<receiver android:name=".MainActivity$browserReceiver"
    android:enabled="true" >
    <intent-filter>
        <action android:name="com.mycompany.snapbench.browsertest" />
    </intent-filter>
</receiver>

在我的 MainActivity 类中:

public static BrowserReceiver browserReceiver;

MainActivity->onCreate:

browserReceiver = new BrowserReceiver();

最后,在 MainActivity 类的末尾:

public class BrowserReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("Receiver", "I'm pretty sick of this.");
    }
}

当我按下应用程序中的按钮时,我会运行它作为测试:

if (isIntentAvailable(this, "com.mycompany.snapbench.browsertest")) {
    Log.e("Intent", "It is there.");
} else {
    Log.e("Intent", "FAIL");
}

当然,我在 LogCat 中总是得到“FAIL”。我究竟做错了什么?

4

2 回答 2

4

刚刚测试了两种方法,都运行良好。对于这两者,我SmsReceiver在一个名为的活动中实现了一个类ContactManager

public static class SmsReceiver extends BroadcastReceiver {

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

    @Override
    public void onReceive(final Context context, final Intent intent) {     
        if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
            Log.d("TAG", "SMS received in inner class");
        }
    }
}
  1. 首先我在onCreate()方法中注册了接收器:

    IntentFilter filter = new IntentFilter(SmsReceiver.SMS_RECEIVED);
    BroadcastReceiver receiver = new SmsReceiver();
    registerReceiver(receiver, filter);
    

    实际上,最好将其注册onResume()并取消注册onPause()

  2. 其次,我删除了我的注册码并将接收器添加到清单中:

两种解决方案都运行良好,并打印了在内部类中收到的文本 SMS。据我所知,您没有声明您的内部类static。那可能是错误。所以只需将其更改为:

public static class BrowserReceiver extends BroadcastReceiver {
    ...
}

希望这会有所帮助......干杯!

于 2013-04-25T20:11:43.297 回答
0

打电话registerReceiveronCreateMainActivity

registerReceiver(browserReceiver, new IntentFilter("com.mycompany.snapbench.browsertest"));  

记得unregisterReceiver(browserReceiver)onDestroy.

于 2013-04-25T19:44:26.210 回答