从服务更新活动的ArrayAdapter

时间:2018-03-29 14:25:54

标签: java android android-arrayadapter

我是Android开发的新手,并且已经跟随tutorial为我的移动应用程序设置了蓝牙活动。我从教程中获得了代码,但后来需要将我的蓝牙代码移到服务上。在移动代码的过程中,我在代码更新ArrayAdapter时遇到问题。

//BluetoothService.java
public void discover(View view){
    //Check if the device is already discovering
    if(bluetoothAdapter.isDiscovering()){
        bluetoothAdapter.cancelDiscovery();
        Toast.makeText(getApplicationContext(), "Discovery stopped", Toast.LENGTH_SHORT).show();
    } else {
        if(bluetoothAdapter.isEnabled()){
            bluetoothAdapter.startDiscovery();
            Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
            registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        } else {
            Toast.makeText(getApplicationContext(), "Bluetooth is not on", Toast.LENGTH_SHORT).show();
        }
    }
}

final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_FOUND.equals(action)){
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            // Add the name to the list
            String deviceName = device.getName();
            bluetoothArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            bluetoothArrayAdapter.notifyDataSetChanged();

        }
    }
};

BroadcastReceiver中,bluetoothArrayAdapter未定义,因为它在活动中定义。该活动只需调用discover函数:

//BluetoothActivity.java
private void discover(View view){
    bluetoothArrayAdapter.clear(); //Clear items
    bluetoothService.discover(view);
}

对Android和Java不熟悉,我不应该如何更新ArrayAdapter。我应该创建一个数组来返回活动,然后用于更新bluetoothArrayAdapter吗?

0 个答案:

没有答案