Android:将自定义线程中的数据发布到选项卡式活动中的不同(片段)布局

时间:2017-04-26 11:08:39

标签: android multithreading queue handler message

我的小安卓项目需要一些帮助。 所以,我必须在一个线程中收集数据。我已经创建了一个线程和处理程序来向ui线程发送消息。这适用于简单的活动。 但问题出现了:我想以不同的方式显示数据:“实时数据”=在文本视图中,数据在图表中,以及之前的(历史数据)。 因此,为此,我创建了一个带有3个片段的标签式活动(一个用于实时数据,一个用于图表,一个用于historycal图表)。但是所有这些片段都需要来自我的线程的相同数据(除了需要最后5-10的最后一个片段,我不知道有多少数据)。 那么我应该从哪里开始阅读?我有什么选择?我应该在这些片段中使用相同的处理程序吗?如果是,我该如何引用它们?或者我必须让我有点困惑,请帮助我。

这是“主要”选项卡式活动(请注意,来自该主题的消息是虚拟数据):

public class ThermoMeasurementActivity extends AppCompatActivity {

private final int SENSOR_POS_BOTTOM = 0x00;
private final int SENSOR_POS_TOP = 0xFF;

private Handler handler;





/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_thermo_measurement);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    handler = new Handler() {

        public void handleMessage(Message msg) {

            String aResponse = msg.getData().getString("message");

            if ((null != aResponse)) {

                Log.d("mytag", "Temp = " + aResponse);
            }
            else
            {
                Log.d("mytag", "Temp = " + aResponse);
            }

        }
    };

    ThermoReaderTask thermoReaderTask = new ThermoReaderTask(handler, SENSOR_POS_BOTTOM, 1000);
    thermoReaderTask.start();
    ThermoReaderTask thermoReaderTask2 = new ThermoReaderTask(handler, SENSOR_POS_TOP, 1000);
    thermoReaderTask2.start();

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_thermo_measurement, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */


/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        switch (position) {
            case 0:
                ThermoMeter tabThermoMeter = new ThermoMeter();
                return tabThermoMeter;
            case 1:
                RealTimeThermoChart rtThermoChart = new RealTimeThermoChart();
                return rtThermoChart;
            case 2:
                HistoryChart historyChart = new HistoryChart();
                return historyChart;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Thermo Meter";
            case 1:
                return "Real Time Chart";
            case 2:
                return "History Chart";
        }
        return null;
    }
}



public class ThermoReaderTask extends Thread
{

    private Handler handler;
    int looptime;
    int sensorPos;

    ThermoReaderTask(Handler handler, int sensorPos, int looptime)
    {
        this.handler = handler;
        this.looptime = looptime;
        this.sensorPos = sensorPos;
    }

    @Override
    public void run() {
        try {
            while(true) {
                String msg = "error";
                if(sensorPos == SENSOR_POS_BOTTOM)
                {
                    msg = "BOTTOM TEMP = 28";
                }else if(sensorPos == SENSOR_POS_TOP)
                {
                    msg = "TOP TEMP = 28";
                }
                Message msgObj = handler.obtainMessage();
                Bundle b = new Bundle();
                b.putString("message", msg);

                msgObj.setData(b);
                handler.sendMessage(msgObj);

                sleep(looptime);
            }
        } catch (Throwable t) {

        }
    }

}
}

这里有一个片段(请注意,评论的部分只是尝试):

public class ThermoMeter extends Fragment implements 
CompoundButton.OnCheckedChangeListener {

private int TEMP_MODE_TOP = 0x00;
private int TEMP_MODE_BOTTOM = 0x00;
private final int SENSOR_POS_BOTTOM = 0x00;
private final int SENSOR_POS_TOP = 0xFF;

private ImageView imgvUnitTop;
private ImageView imgvUnitBottom;
private ToggleButton tbTempTop;
private ToggleButton tbTempBottom;
private Handler handler;
private TextView tvTempTop;
private TextView tvTempBottom;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab1thermometer, container, false);

    imgvUnitTop = (ImageView)rootView.findViewById(R.id.imgvTop);
    tbTempTop = (ToggleButton)rootView.findViewById(R.id.tbTempTop);
    imgvUnitBottom = (ImageView)rootView.findViewById(R.id.imgvBottom);
    tbTempBottom = (ToggleButton)rootView.findViewById(R.id.tbTempBottom);
    tbTempBottom.setOnCheckedChangeListener(this);
    tbTempTop.setOnCheckedChangeListener(this);
    tvTempTop = (TextView)rootView.findViewById(R.id.tvTempTop);
    tvTempBottom = (TextView)rootView.findViewById(R.id.tvTempBottom);

     /*handler = new Handler() {

        public void handleMessage(Message msg) {

            String aResponse = msg.getData().getString("message");

            if ((null != aResponse)) {

                Log.d("mytag", "Temp = " + aResponse);
            }
            else
            {
                Log.d("mytag", "Temp = " + aResponse);
            }

        }
    };*/


  /*  ThermoReaderTask thermoReaderTask = new ThermoReaderTask(handler, SENSOR_POS_BOTTOM, 1000);
    thermoReaderTask.start();
    ThermoReaderTask thermoReaderTask2 = new ThermoReaderTask(handler, SENSOR_POS_TOP, 1000);
    thermoReaderTask2.start();*/
    return rootView;
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView.getId() == R.id.tbTempTop) {
        if(isChecked)
        {
            TEMP_MODE_TOP = 0x00;
            imgvUnitTop.setImageResource(R.drawable.celsius);
        }else
        {
            TEMP_MODE_TOP = 0xFF;
            imgvUnitTop.setImageResource(R.drawable.fahrenheit);
        }
    }
    else if(buttonView.getId() == R.id.tbTempBottom){
        if(isChecked)
        {
            TEMP_MODE_BOTTOM = 0x00;
            imgvUnitBottom.setImageResource(R.drawable.celsius);
        }else
        {
            TEMP_MODE_BOTTOM = 0xFF;
            imgvUnitBottom.setImageResource(R.drawable.fahrenheit);
        }
    }
}

}

你能给我一些链接,教程,提示吗?

0 个答案:

没有答案