2013-02-17 80 views
0

我有以下代码开始活动,代码是当用户点击Android设备上的菜单按钮时出现的子菜单,它的问题是,当按钮被点击一个新的活动开始了,这会丢失之前形成的蓝牙连接!新的活动开始于意图

@Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     Intent serverIntent = null; 
     Intent PassIntent; 
     Intent PassIntent1; 
     switch (item.getItemId()) { 
     /*case R.id.home: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, engineStarter.class); 
      startActivity(serverIntent); 
      return true;*/ 
     /*case R.id.insecure_connect_scan: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, DeviceListActivity.class); 
      startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); 
      return true;*/ 
     /*case R.id.discoverable: 
      // Ensure this device is discoverable by others 
      ensureDiscoverable(); 
      return true;*/ 
     case R.id.setpassword: 
      PassIntent = new Intent(this, SetPassword.class); 
      startActivity(PassIntent); 
      return true; 
     case R.id.home: 
      // Launch the DeviceListActivity to see devices and do scan 
      serverIntent = new Intent(this, engineStarter.class); 
      startActivity(serverIntent); 
      return true; 
     } 
     return false; 
    } 
+0

我真正想要的只是加载活动与以前的状态,而不是再次创建活动性和松散的连接! – Naaz 2013-02-17 20:02:38

+0

为什么不通过服务来管理蓝牙连接? – 2013-02-17 20:38:22

+0

我试过了,但我记得我被卡在某个地方,所以只是没有这样去! – Naaz 2013-02-17 21:05:55

回答

1

你有两个选择:

1-更改您的活动的启动模式android:launchMode="singleTask",因此它不创建一个新的实例每次调用startActivity

2-时间保持你Bluetooth连接在一个service

还有另一种可能的解决方案,但可能不是优雅之一,是定义一个自定义的application类,你可以维护在这种情况下,Bluetooth连接将会紧挨着applicationContext

+0

谢谢我会尝试一个使用singleTask的选项 – Naaz 2013-02-17 21:04:24

+0

“还有另一种可能的解决方案,但可能不太好,它是定义一个自定义应用程序类,您可以在其中维护蓝牙连接” - 我只是在做同样的事情这一次,但我认为我不会将它绑定到相同的背景下,你可以在这方面进一步阐述一下吗? – Naaz 2013-02-17 21:05:22

+0

发布你的代码,因为我不知道你在做什么。 – iTech 2013-02-17 21:11:23

0

另一种方法是保持相同的Activity,但将新的fragments加载到替换当前片段的活动中。使用FragmentManager时,您可以将新片段推送到堆栈以向前导航并将其弹出以向后导航。这将允许您浏览内容并保持蓝牙连接。