簡體   English   中英

新活動始於Intent

[英]Fresh Activity starts on Intent

我有以下代碼可以啟動活動,該代碼適用於用戶在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;
    }

您有兩種選擇:

1-將您的活動的啟動模式更改為android:launchMode="singleTask" ,因此不會在您每次調用startActivity時創建一個新實例

2-維護service Bluetooth連接

還有另一種可能的解決方案,但可能不是一個很優雅的解決方案:定義一個自定義application類,您可以在其中維護Bluetooth連接,在這種情況下, Bluetooth連接與applicationContext緊密相關。

一種替代方法是保留相同的Activity,但將新片段加載到Activity中以替換當前片段。 使用FragmentManager時,您可以將新片段推入堆棧以向前導航,然后將其彈出以向后導航。 這將允許您瀏覽內容並保持藍牙連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM