2014年6月9日 星期一

Android 4.3 的Thread應用:
package com.example.smartheartrate;

import java.util.Random;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends Activity {

static int count = 0;

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


if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);

System.out.println("start in");
final TextView wordToGuess = (TextView) rootView.findViewById(R.id.text);


final Handler hr;
hr = new Handler(){
            public void handleMessage(Message msg) {
                switch(msg.what){
               
                case 1:
                 
                int newvalue = -1;
           
                do{
                newvalue = new Random().nextInt(120);
               
                }while(newvalue < 88);              
               
                    wordToGuess.setText("HR:"+ newvalue);
               
                break;
                }                        
                super.handleMessage(msg);
            }
       };
     
       new Thread(new Runnable(){
           public void run(){
             
               while(true){
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }

               Message m = new Message();                              
                m.what = 1;              
                hr.sendMessage(m);              
               }                      
           }
       }).start();


return rootView;
}
}

}

沒有留言:

張貼留言