strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Intent</string>
<string name="start">开始</string>
<string name="stop">停止</string>
</resources>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:id="@+id/startButtonId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center"
android:text="@string/start" android:layout_margin="10px" />
<Button android:id="@+id/stopButtonId" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="center"
android:text="@string/stop" android:layout_margin="10px" />
</LinearLayout>
IntentActivity.java
package com.duoguo.android;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Intent的使用
*
* @author shyboy(897948924@qq.com)
*
*/
public class IntentActivity extends Activity {
// 声明Button控件
private Button startButton;
private Button stopButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 根据Button控件的id获取控件对象
startButton = (Button) findViewById(R.id.startButtonId);
stopButton = (Button) findViewById(R.id.stopButtonId);
startButton.setOnClickListener(new StartButtonClickListener());// 为startButton添加单击事件监听器
stopButton.setOnClickListener(new StopButtonClickListener());// 为stopButton添加单击事件监听器
}
// 声明startButton控件的监听器
class StartButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
handler.post(runnable);// 将线程添加到消息队列中
}
}
// 声明stopButton控件的监听器
class StopButtonClickListener implements OnClickListener {
@Override
public void onClick(View v) {
handler.removeCallbacks(runnable);// 在消息队列中将行将发生的post进行移除
}
}
Handler handler = new Handler();// 实例化Handler对象
// 实例化线程runnable对象
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("runnable……");
handler.postDelayed(runnable, 3000);// 在3秒时间过后将线程添加到消息队列中
}
};
}
希望能够给你带来帮助
分享到:
评论