2

嗨,我正在使用广播接收器进行位置侦听,但是此广播接收器仅在活动处于前台时才起作用,否则当我不使用此应用程序时,接收器不活动这里是活动代码 onCreate 的方法,我在其中注册广播接收器

 PendingIntent proximityIntent = PendingIntent.getBroadcast(getApplicationContext(), i, intent, PendingIntent.FLAG_UPDATE_CURRENT);



locationManager.addProximityAlert(

           latitude, // the latitude of the central point of the alert region

           longitude, // the longitude of the central point of the alert region

           1000, // the radius of the central point of the alert region, in meters

           -1, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration

           proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected

      );

IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT+s); 

     registerReceiver(new ProximityAlertReceiver(), filter);

BroadcastReceiver 的代码是

public class ProximityAlertReceiver extends BroadcastReceiver {



    private static final int NOTIFICATION_ID = 1000;
    public static final String PREFS_NAME = "MyPrefsFile";


    @Override

    public void onReceive(Context context, Intent intent) {



        String key = LocationManager.KEY_PROXIMITY_ENTERING;
SharedPreferences shared=context.getSharedPreferences(MainActivity.PREFS_NAME,0);


        Boolean entering = intent.getBooleanExtra(key, false);
Double longitude=intent.getDoubleExtra("longitude", 0.0);
Double latitude=intent.getDoubleExtra("latitude",0.0);

Intent in = new Intent(context,AlarmActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("longitude", longitude);
in.putExtra("latitude", latitude);
Log.i("cont1", shared.getInt("count", 0)+"");
in.putExtra("count",shared.getInt("count", 0));
context.startActivity(in);
}

}

我读了一些分别在 onResume 和 onPause 方法中注册和取消注册它的地方,但是当我在 onPause 方法中取消注册它时,它被取消注册意味着它不会工作我希望我的广播接收器一直工作。你能建议如何做到这一点。

4

4 回答 4

4

如果你想让它在后台工作,你需要在清单文件中添加广播接收器和广播接收器类。

喜欢这个教程http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html

您可以使用自己的“MyReceiver”。

在这种情况下,您不需要注册和取消注册。这将自动工作。

于 2012-12-14T04:51:51.620 回答
1

如果你想让你的广播接收器一直运行,你需要从清单文件中注册它。来自文档:您可以使用 Context.registerReceiver() 动态注册此类的实例,也可以通过 AndroidManifest.xml 中的标记静态发布实现。

http://developer.android.com/reference/android/content/BroadcastReceiver.html

于 2012-12-14T04:57:33.657 回答
0

我认为服务类将帮助您,尝试在后台实现....无限次,当您的服务发现某些内容发生更改时,它会发送一些广播。给你 :)

于 2013-04-18T05:00:40.450 回答
0

首先你被定义为 mainfest 所以应用程序也没有运行它们广播接收器工作..所以你可以使用 PackageManager 处理这种类型的广播并获取包名称如果启用或禁用你可以检查并运行你的 brodcast

于 2012-12-14T05:10:43.957 回答