首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在应用程序关闭后保存BluetoothDevice对象

在应用程序关闭后保存BluetoothDevice对象
EN

Stack Overflow用户
提问于 2012-12-11 02:50:13
回答 2查看 5.1K关注 0票数 5

我想保存我的应用程序连接到的最后一个蓝牙设备。如果之前有蓝牙连接,我希望根本不提示用户。他们可以选择连接到新设备,但他们不需要这样做。如果他们选择不选择连接,他们将定期使用应用程序,然后当需要蓝牙设备时,它将连接到最新的设备。

我已经尝试使用下面的Tudor Luca's answer中提供的代码,但对象不会写入文件。我要买一台NotSerializableException。我尝试保存的对象是用import android.bluetooth.BluetoothDevice导入的BluetoothDevice

这就是我试图使蓝牙设备可序列化的方法:

代码语言:javascript
复制
import java.io.Serializable;
import android.bluetooth.BluetoothDevice;

public class SerializableObjects implements Serializable {
    private BluetoothDevice device;

    public SerializableObjects( BluetoothDevice device ) {
        this.device = device;
    }

    public BluetoothDevice getDevice() {
        return this.device;
    }
}

LogCat返回以下内容:

代码语言:javascript
复制
12-11 17:46:24.032: W/System.err(24641): java.io.NotSerializableException: android.bluetooth.BluetoothDevice
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1535)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:1143)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:413)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1241)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1575)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1847)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1689)
12-11 17:46:24.032: W/System.err(24641):    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1653)
12-11 17:46:24.032: W/System.err(24641):    at my.eti.commander.LocalObjects.writeObjectToFile(LocalObjects.java:29)
12-11 17:46:24.032: W/System.err(24641):    at my.eti.commander.MainMenu$1.handleMessage(MainMenu.java:460)
12-11 17:46:24.032: W/System.err(24641):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-11 17:46:24.036: W/System.err(24641):    at android.os.Looper.loop(Looper.java:130)
12-11 17:46:24.036: W/System.err(24641):    at android.app.ActivityThread.main(ActivityThread.java:3687)
12-11 17:46:24.036: W/System.err(24641):    at java.lang.reflect.Method.invokeNative(Native Method)
12-11 17:46:24.036: W/System.err(24641):    at java.lang.reflect.Method.invoke(Method.java:507)
12-11 17:46:24.036: W/System.err(24641):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
12-11 17:46:24.036: W/System.err(24641):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-11 17:46:24.036: W/System.err(24641):    at dalvik.system.NativeStart.main(Native Method)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-13 05:38:23

没有办法直接序列化BluetoothDevice类。即使您序列化了它,我也不认为您能够在应用程序关闭后重用该对象。相反,我有一个helper类,它将存储设备的地址。您可以保存设备地址和名称,并在以后读取该信息。然后,您可以执行绑定设备的发现/搜索,并获得相应的设备。

下面是我通常使用的帮助器类

代码语言:javascript
复制
public class BluetoothState implements Serializable {
    public static final int STATE_NOT_CONNECTED = 1;
    public static final int STATE_CONNECTED = 1;

    public static final String filename = "btState.pref";

    public static int connectionState = STATE_NOT_CONNECTED;
    public static String deviceAddress = "00:00:00:00:00:00";
    public static String deviceName = "";

    public static void setConnectionState(boolean connected,BluetoothDevice device) {
        if(connected)
            connectionState = STATE_CONNECTED;
        else
            connectionState = STATE_NOT_CONNECTED;

        if(device != null) {
            deviceAddress = device.getAddress();
            deviceName = device.getName();
        }

    }

    public static void saveConnectionState(Context cxt) throws IOException {        
        FileOutputStream fos = cxt.openFileOutput(filename, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);       
        oos.writeInt(connectionState);
        oos.writeUTF(deviceAddress);
        oos.writeUTF(deviceName);
    }

    public static void loadConnectionState(Context cxt) throws IOException {        
        FileInputStream fis = cxt.openFileInput(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);     
        connectionState = ois.readInt();
        deviceAddress = ois.readUTF();
        deviceName = ois.readUTF();
    }

    public static BluetoothDevice getDevice() {
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if(!btAdapter.isEnabled())
            btAdapter.enable();

        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();

        for(BluetoothDevice d : pairedDevices)
            if(d.getAddress().equalsIgnoreCase(deviceAddress))
                return d;

        return null;        
    }

}
票数 2
EN

Stack Overflow用户

发布于 2012-12-11 03:00:35

你可以把你的对象写到一个私有文件中,然后从那里加载它。你唯一需要对你的对象做的事情,就是让它成为implements Serializable

代码语言:javascript
复制
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.content.Context;

/**
 *
 * Writes/reads an object to/from a private local file
 * 
 *
 */
public class LocalObjects{


    /**
     * 
     * @param context
     * @param object
     * @param filename
     */
    public static void witeObjectToFile(Context context, Object object, String filename) {

        ObjectOutputStream objectOut = null;
        try {

            FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
            objectOut = new ObjectOutputStream(fileOut);
            objectOut.writeObject(object);
            fileOut.getFD().sync();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOut != null) {
                try {
                    objectOut.close();
                } catch (IOException e) {
                    // do nowt
                }
            }
        }
    }


    /**
     * 
     * @param context
     * @param filename
     * @return
     */
    public static Object readObjectFromFile(Context context, String filename) {

        ObjectInputStream objectIn = null;
        Object object = null;
        try {

            FileInputStream fileIn = context.getApplicationContext().openFileInput(filename);
            objectIn = new ObjectInputStream(fileIn);
            object = objectIn.readObject();

        } catch (FileNotFoundException e) {
            // Do nothing
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectIn != null) {
                try {
                    objectIn.close();
                } catch (IOException e) {
                    // do nowt
                }
            }
        }

        return object;
    }

}

所以基本上,你想做的就是得到最后一对设备,对吧?下面是代码应该是什么样子:

  1. 所有蓝牙活动都需要BluetoothAdapter

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (mBluetoothAdapter == null) {

//Then your device does not support Bluetooth

}

  • Make确保蓝牙已启用

if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }

  • Get以前配对的设备

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } }

有关如何使用蓝牙连接的完整教程,请查看this

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13807241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档