2013-02-21 62 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);