简体   繁体   中英

How to pass a BluetoothAdapter from one activity to another in Android?

I have a class / activity called MainActivity.java where I have used a BluetoothAdapter BA to check if the Bluetooth is on or not. I have another class called Search.java that searches for nearby Bluetooth devices, but it has to do so using the same BluetoothAdapter created in MainActivity.java. How do I do that?

And also I have a button in my MainAactivity.java whose onClick has to be defined in another class, how do I do that?

I'm sorry if such questions are stupid, but I'm new to Android & have very little experience working with Java.

Thanks for your time!

I have a class / activity called MainActivity.java where I have used a BluetoothAdapter BA to check if the Bluetooth is on or not. I have another class called Search.java that searches for nearby Bluetooth devices, but it has to do so using the same BluetoothAdapter created in MainActivity.java. How do I do that?

(Edit: please see my edit below, you don't need to implement this in your case) You can implement a Singleton to store and get the BluetoothAdapter, so you can access it anywhere in your project. It would be something like this:

import android.bluetooth.BluetoothAdapter;

public class BluetoothSingleton {
    private static BluetoothSingleton mInstance = new BluetoothSingleton();
    private BluetoothAdapter mBluetoothAdapter;

    private BluetoothSingleton(){
        // Private constructor to avoid new instances
    }

    public static BluetoothSingleton getInstance(){
        return mInstance;
    }

    public void setBluetoothAdapter(BluetoothAdapter adapter){
        mBluetoothAdapter = adapter;
    }

    public BluetoothAdapter getBluetoothAdapter(){
        return mBluetoothAdapter;
    }
}

And also I have a button in my MainActivity.java whose onClick has to be defined in another class, how do I do that?

You can simply create a method to set that button listener, passing a OnClickListener like this:

AnotherClass.java:

...
public void setButtonListener(View.OnClickListener listener){
    mButton.setOnClickListener(listener);
}
...

Then you can set it in your MainActivity.java:

...
AnotherClass another = new AnotherClass();
another.setButtonListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Do what you want here
        }
    });
...

EDIT 1:

Actually BluetoothAdpater is a singleton , so you can just call:

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

And you will get the same adapter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM