我不知道我的信标应用程序需要什么内容

时间:2014-10-23 10:48:11

标签: java android

这是我的代码:

public class MainActivity extends Activity {
    private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
    private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId",
        ESTIMOTE_PROXIMITY_UUID, null, null);
    public String TAG = "Beacons";

    private BeaconManager beaconManager = new BeaconManager(context);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    beaconManager.setRangingListener(new BeaconManager.RangingListener() {
        @Override
        public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
            Log.d(TAG, "Ranged beacons: " + beacons);
        }
    });
}

...

问题出在第23行:

private BeaconManager beaconManager = new BeaconManager(context);

我用什么来代替“背景”?

谢谢。

2 个答案:

答案 0 :(得分:2)

更有效的方法是声明全局Context并在onCreate()方法中初始化它。它使您可以将相同的上下文用于其他方法,例如显示Toast。

public class MainActivity extends Activity {
private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId",
  ESTIMOTE_PROXIMITY_UUID, null, null);
public String TAG = "Beacons";
private Context  context;
private BeaconManager beaconManager;

@Override 
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
beaconManager = new BeaconManager(context);
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
    @Override 
    public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
        Log.d(TAG, "Ranged beacons: " + beacons);
    } 
}); 

}

答案 1 :(得分:1)

Context是一个提供有关应用程序环境的全局信息的接口。 每个活动都扩展了Context。这就是为什么你可以写this而不是上下文。

private BeaconManager beaconManager = new BeaconManager(this)