蓝牙流媒体是落后的Android应用程序

时间:2015-09-12 14:04:25

标签: android bluetooth stream lag

我正在编写通过蓝牙从其他设备接收数据的Android应用程序。这些数据实际上是不间断的流媒体。在获得大约50或70个之后,app减速并停止向我显示收到的数据。应用缓存已满,但清除它(删除context.getCacheDir())并没有帮助。重新启动整个应用程序后,我可以再次获取下一部分数据。我可以做些什么来避免这种情况"滞后"?

我的MainActivity:

public class MainActivity extends Activity {
    private BluetoothAdapter bluetoothAdapter;
    private boolean pendingRequestEnableBt = false;
    private final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
    private BluetoothResponseHandler mHandler;
    private static MainActivity instance;
    private DeviceConnector connector;
    private TextView console;
    private String deviceName;

    private final int REQUEST_CONNECT_DEVICE = 1;
    private final int REQUEST_ENABLE_BT = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        instance = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        console = (TextView) findViewById(R.id.main_text_console);
        if (savedInstanceState != null) {
            pendingRequestEnableBt = savedInstanceState.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
        }
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "No bluetooth available", Toast.LENGTH_LONG).show();
        }
        if (mHandler == null) {
            mHandler = new BluetoothResponseHandler(this);
        } else {
            mHandler.setTarget(this);
        }
    }

    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
        getActionBar().setSubtitle(deviceName);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
        outState.putString("device_name", deviceName);
        if (console != null) {
            final String log = console.getText().toString();
            outState.putString("AC", log);
        }
    }

    public boolean isAdapterReady() {
        return (bluetoothAdapter != null) && (bluetoothAdapter.isEnabled());
    }

    private static class BluetoothResponseHandler extends Handler {
        private WeakReference<MainActivity> mActivity;

        public BluetoothResponseHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        public void setTarget(MainActivity target) {
            mActivity.clear();
            mActivity = new WeakReference<MainActivity>(target);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            if (activity != null) {
                if (msg.what==MessageType.MESSAGE_STATE_CHANGE.getValue()) {
                    final ActionBar bar = activity.getActionBar();
                    switch (msg.arg1) {
                        case DeviceConnector.STATE_CONNECTED:
                            bar.setSubtitle("Połączono.");
                            break;
                        case DeviceConnector.STATE_CONNECTING:
                            bar.setSubtitle("Łączenie");
                            break;
                        case DeviceConnector.STATE_NONE:
                            bar.setSubtitle("Rozłączono.");
                            break;
                    }
                } else if (msg.what==MessageType.MESSAGE_READ.getValue()) {
                    if (msg.obj != null) {
                        activity.appendLog((String)msg.obj);
                    }
                } else if (msg.what==MessageType.MESSAGE_DEVICE_NAME.getValue()) {
                    activity.setDeviceName((String) msg.obj);
                }
            }
        }
    }

    private void startDeviceListActivity() {
        stopConnection();
        startActivityForResult(new Intent(this, DeviceListActivity.class), REQUEST_CONNECT_DEVICE);
    }

    private void stopConnection() {
        if (connector != null) {
            connector.stop();
            connector = null;
        }
    }

    @Override
    public boolean onSearchRequested() {
        if (isAdapterReady()) {
            startDeviceListActivity();
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.device_control_activity, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
                    if (isAdapterReady() && (connector == null)) setupConnector(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                pendingRequestEnableBt = false;
                if (resultCode != Activity.RESULT_OK) {
                    Toast.makeText(this, "Bt not enabled", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void setupConnector(BluetoothDevice connectedDevice) {
        stopConnection();
        connector = new DeviceConnector(new DeviceData(connectedDevice, getString(R.string.empty_device_name)), mHandler);
        connector.connect();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_search:
                if (isAdapterReady()) {
                    if (isConnected()) {
                        stopConnection();
                    } else {
                        startDeviceListActivity();
                    }
                } else {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void appendLog(String message) {
        String msg = message.replaceAll("[\n\t\r ]*", "");
        console.append(msg.length() + ": " + msg + "\n");
        final int scrollAmount = console.getLayout().getLineTop(console.getLineCount()) - console.getHeight();
        console.scrollTo(0, scrollAmount>0?scrollAmount:0);
        delete(getCacheDir());
    }

    private boolean isConnected() {
        return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
    }

    public static MainActivity getInstance() {
        return instance;
    }

    public void delete(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                for (File f:file.listFiles()) {
                    delete(f);
                }
            }
        }
    }
}

此代码已下载,它不是我的,我只是修改了它。

0 个答案:

没有答案