Android以最快的方式将服务发送到Activity

时间:2017-08-06 03:13:03

标签: android bluetooth android-broadcast

我正在开发一个项目,Arduino通过蓝牙向Android发送持续的数据流。数据速率低于预期,我正在调查Arduino和Android程序以找到瓶颈,这就是我发现的。 我认为瓶颈在于android蓝牙服务与活动之间的沟通。我正在使用本地广播将数据从服务发送到活动,我注意到即使在Arduino停止发送数据之后,广播也会继续进行活动。因此,我得出结论,瓶颈必须与我的蓝牙服务向活动发送数据的方式有关。

起初,我正在使用广播经理,然后我切换到本地广播经理,看到了一些改进,但没有任何突破性的。我想知道是否有人知道我将数据从Service发送到Activity的最快方式。

1 个答案:

答案 0 :(得分:0)

有很多方法。 我建议使用Intend,因为它很容易

public class SomeActivity extends Activity{
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        receiver = new MyBroadcastReceiver();
        this.registerReceiver(receiver, new IntentFilter(MyBroadcastReceiver.ACTION));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(receiver);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver{
        public static final String ACTION = "com.example.ACTION_SOMETHING"
        @Override
        public void onReceive(Context context, Intent intent) {
            String test = intent.getStringExtra("dataToPass");
        }
    }
} 

发送到服务类

中的活动
Intent intent = new Intent();
intent.setAction(SomeActivity.MyBroadcastReceiver.ACTION);
intent.putExtra("dataToPass", test);
context.sendBroadcast(intent);