为什么广播接收器永远不会被调用?

时间:2016-01-30 17:37:59

标签: android events gps broadcastreceiver

在我的 MainActivity 中,我正在创建接收器并发送广播:

GPSStartedReceiver receiver = new GPSStartedReceiver();
this.registerReceiver(receiver, new IntentFilter("android.location.GPS_ENABLED_CHANGE"));
Intent intent = new Intent();
intent.setAction("com.test.broadcastReceiver.GPSStartedReceiver()");
sendBroadcast(intent);

但是当我启用 GPS 时,广播接收器没有被调用。

以下是清单中接收器的一部分:

<receiver android:name="com.test.broadcastReceiver.GPSStartedReceiver">
        <intent-filter>
            <action android:name="android.location.GPS_ENABLED_CHANGE" />
        </intent-filter>
</receiver>

广播接收器

    public class GPSStartedReceiver extends BroadcastReceiver {

    // Start service 5 seconds after GPS is enabled
    private static final long WAIT_TIME = 1000 * 5;
    // Restart service every 30 seconds
    private static final long REPEAT_TIME = 1000 * 30;

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

        if (intent.getAction().equals("android.location.GPS_ENABLED_CHANGE")) {

            final Handler handler = new Handler();

            Toast.makeText(context,
                    context.getResources().getString(R.string.starting_in_5),
                    Toast.LENGTH_SHORT).show();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    AlarmManager service = (AlarmManager) context
                            .getSystemService(Context.ALARM_SERVICE);
                    Intent i = new Intent(context, GPSTracker.class);
                    PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
                            PendingIntent.FLAG_CANCEL_CURRENT);
                    Calendar cal = Calendar.getInstance();
                    // Start 30 seconds after boot completed
                    cal.add(Calendar.SECOND, 30);
                    // Fetch every 30 seconds
                    service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                            cal.getTimeInMillis(), REPEAT_TIME, pending);
                }
            }, WAIT_TIME);

        }
    }
}

为什么接收器永远不会被呼叫,即使我启用 GPS

2 个答案:

答案 0 :(得分:0)

您是否尝试过注册BroadcastReceiver以收听Intent Action PROVIDERS_CHANGED_ACTION?如果这不起作用,您可以获取locationManager的实例,然后向其注册GpsStatusListener,如下所示mLocationManager.addGpsStatusListener(new android.location.GpsStatus.Listener())并使用其内部方法。

希望有所帮助

答案 1 :(得分:0)

使用 PROVIDERS_CHANGED_ACTION 在API级别9中添加当配置的位置提供商更改时的广播意图操作。用于isProviderEnabled(String)。如果您正在与LOCATION_MODE API进行交互,请改用MODE_CHANGED_ACTION。

常量值:“android.location.PROVIDERS_CHANGED”

您可以在this SO post

找到解决方案