在我的应用程序中,我使用Janos Gyerik 的 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: Unable to create .MyService: NullPointerException