Update android Textview continuously

前端 未结 4 1051
执笔经年
执笔经年 2021-01-22 12:27

I am working on an Android Application which have an one activity class and service class. In service, Continuous bulk data (1090 by

4条回答
  •  花落未央
    2021-01-22 12:58

    User LocalBroadcastManager

    public void Receivepatientattributes(byte[] readBuf, int len) {
        String total_data = "";
        total_data = bytetohex(readBuf, len);
    
        Intent intent = new Intent("update-text");
        // add data
        intent.putExtra("message", total_data);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    

    In MainActivity

    @Override
    public void onResume() {
      super.onResume();
    
      // Register mMessageReceiver to receive messages.
      LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
          new IntentFilter("update-text"));
    }
    
    private boolean mCanBeUpdated = true;
    private static final int ONE_SEC = 1000; //ms
    private static final int RECEPTION_SPEED = 10; //ms
    private static final int CYCLES = (int) (ONE_SEC / RECEPTION_SPEED);
    private int mCurrentCycle = -1;
    private String mMsgCache = "";
    
    // handler for received Intents for the "update-text" event 
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Extract data included in the Intent
            String message = intent.getStringExtra("message");
            Log.d("receiver", "Got message: " + message);
    
            mMsgCache = mMsgCache + "\t" + message;
    
            if (mCanBeUpdated) {
                // No problem updating UI here, refer --> http://stackoverflow.com/a/5676888/1008278
                final Handler handler = new Handler(context.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        MainActivity.recep.append(mMsgCache);
                        mMsgCache = "";
                    }
                });
    
                mCanBeUpdated = false;
            } else if (mCurrentCycle >= CYCLES) {
                mCurrentCycle = -1;
                mCanBeUpdated = true;
            } else {
                mCurrentCycle++;
            }
        }
    };
    
    @Override
    protected void onPause() {
      // Unregister since the activity is not visible
      LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
      super.onPause();
    } 
    

    Reference

提交回复
热议问题