ThreadPractice_android

Posted lingyaoyao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ThreadPractice_android相关的知识,希望对你有一定的参考价值。

RandomService.java
public class RandomService extends Service {
private Thread workThread;
private static double random;
@Nullable
@Override
public android.os.IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
workThread = new Thread(null, workRunnable, "work");
Toast.makeText(this, "create()", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start()", Toast.LENGTH_LONG).show();
if(!workThread.isAlive()){
workThread.start();
}
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Destroy()", Toast.LENGTH_LONG).show();
}
Runnable workRunnable = new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()){
try{
random = Math.round(Math.random()*100);
MainActivity.updateGUI(random);
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
}
////////////////////////////////////////////////////////////////////////
MainActivity.java
public class MainActivity extends AppCompatActivity {

private static TextView textView = null;
Button btn_start;
Button btn_stop;
private static Handler handler = new Handler();
private static double random;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.text);
btn_start = (Button)findViewById(R.id.btn_start);
btn_stop = (Button)findViewById(R.id.btn_stop);
final Intent intent = new Intent(this, RandomService.class);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intent);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intent);
}
});
}
public static void updateGUI(double _random){
random = _random;
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(String.valueOf(random));
}
});
}
}




















































































以上是关于ThreadPractice_android的主要内容,如果未能解决你的问题,请参考以下文章