界面资源文件:
rea/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="结束" /> </LinearLayout>
界面效果如图
MainActivity:
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements Runnable{ private Thread thread; int i=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button startButton=(Button)findViewById(R.id.button1);//获取开始按钮 startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { i=0; thread=new Thread(MainActivity.this);//创建一个线程 thread.start();//开启线程 } }); Button endButton=(Button)findViewById(R.id.button2);//获取结束按钮 endButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if(thread!=null){ thread.interrupt();//中断线程 thread=null; } Log.i("提示:", "中断线程"); } }); } @Override public void run() { while(!Thread.currentThread().isInterrupted()){ i++; Log.i("循环变量", String.valueOf(i)); } } @Override protected void onDestroy() { if(thread!=null){ thread.interrupt();//中断线程 thread=null; } Log.i("提示:", "因Activity结束中断线程"); super.onDestroy(); } }
运行结果和按键之后的效果如图所示
转载请注明出处:http://blog.csdn.net/acmman/article/details/46337017