且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过多个活动保持android蓝牙连接

更新时间:2022-03-25 22:53:37

您在哪里存储 BlueComms 类的实例?如果你把它放在第一个活动中,那么当你离开它并移动到下一个活动时该活动被破坏时,类实例就会被杀死(NB活动也会在屏幕旋转时被破坏)

Where did you store the instance of your BlueComms class? If you put it in the first activity then the class instance would have been killed when that activity was destroyed as you left it and moved to the next activity (NB activities also get destroyed on screen rotation)

因此,您需要找到一种方法,使 BlueComms 类的实例在需要时一直保持活动状态.您可以通过公共属性在活动之间传递它,并在轮换期间将其存储在 onRetainNonConfigurationInstance() 中.

So you need to find a way to keep the instance of BlueComms class alive for as long as you need it. You could pass it between activities via public properties and store it in onRetainNonConfigurationInstance() during rotations.

一个更简单的技巧是创建一个扩展 Application 的类,将其用作应用程序的应用程序委托,并向其添加公共属性以在其中存储 BlueComms 类的实例.这样,BlueComms 类的实例将在您的应用程序的整个生命周期内都处于活动状态.

An easier trick is to create a class that extends Application use it as the application delegate for your app and add public property to it to store the instance of BlueComms class within it. That way the instance of BlueComms class would be alive for the lifetime of you app.

扩展应用

import android.app.Application;

public class cBaseApplication extends Application {

    public BlueComms myBlueComms;

    @Override
    public void onCreate() 
    {
        super.onCreate();
        myBlueComms = new BlueComms();
    }

}

使您的类成为应用清单中的应用委托

Make your class the application delegate in the app manifest

<application
    android:name="your.app.namespace.cBaseApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

从您的任何活动访问基本应用程序

Access the base app from any of your Activities like this

((cBaseApplication)this.getApplicationContext()).myBlueComms.SomeMethod();