2013-02-21 44 views
0

在我的应用程序中,我使用Janos Gyerik's BluetoothViewer代码通过蓝牙进行连接。如何保持蓝牙活动有效

我也有一个TCPServer类通过USB连接。

public void connectViaUSB() { 
    if (GlobalVariables.connectionstatus == 0) { 
     mTCPServer = new TCPServer(2222, getCurrentActivity()); 
     mTCPServer.start(); 
     mTCPServer.setResponseReceivedListener(this); 
    } 

问题是,BluetoothViewer写为Activity。一个需要启动连接的活动,但是当我切换到另一个活动连接时会丢失。

我需要一直保持该活动,或找到修改方法。我该如何解决这种情况?

编辑

'
公共类的MyService延伸服务{

private static final String TAG = "MyService"; 

@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onCreate"); 

    BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); 
    mAdapter.enable(); 

    BluetoothChatService mChatService = new BluetoothChatService(mHandler); 
    BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:12:11:13:19:26"); 
    mChatService.connect(device); 
} 

@Override 
public void onDestroy() { 
    Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); 
    //stop thread 
} 

@Override 
public void onStart(Intent intent, int startid) { 
    Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show(); 
    Log.d(TAG, "onStart"); 
    //start thread (again) 
} 

}`

我怎样才能让这个服务类的蓝牙连接?它需要我移动mHandler,而我也是。现在我得到RuntimeException:无法创建.MyService:空指针异常

回答

0

不知道这是否可以帮助你,但我创建了一个机器人,一旦它被蓝牙控制。它使用在服务/线程内运行的连接。为此,我使用以下2类:

BluetoothSerialService.java

DeviceListActivity.java

不仅仅是谷歌的2类,你会发现在那里它们被托管的地方。像这儿。 http://code.google.com/p/bluetooth-remote-control/source/browse/trunk/src/pro/apus/blueremote/?r=2

要实际设置连接,只需将这样的事情绑定到按钮。

public void autoconnect() { 

     t = new TextView(this); 
     t = (TextView) findViewById(R.id.connecttext); 
     mSerialService = new BluetoothSerialService(this, mHandlerBT, t); 
     if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) { 
      BluetoothDevice device = BluetoothAdapter.getDefaultAdapter() 
        .getRemoteDevice(mMacAddress); 
      mSerialService.connect(device); 
     } else if (mSerialService.getState() == BluetoothSerialService.STATE_CONNECTED) { 
      setProgressBarIndeterminateVisibility(false); 
      mSerialService.stop(); 
      mSerialService.start(); 
     } 
    } 

并且确保在做这件事之前征求许可。

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter 
       .getDefaultAdapter(); 
     askBluetoothPermission(mBluetoothAdapter);