在android中有许多控件,如TextView、Button等。他们大多都有监听器,如View类下的单击监听,按键监听等等
有没有想过自己定义一个监听呢?
1.用关键字interface定义接口OnTestListening,通过关键字implements来声明接口;
在接口中我们可以定义接口函数,用来以后监听时重写,可以定义好多,这里我只定义一个;
在类中定义一个公共函数用于设置监听;
具体看以下代码:
1 public interface OnTestListening{ 2 void TestListening(int i); 3 } 4 5 OnTestListening mOnTestListening=null; 6 public void setOnTestListening(OnTestListening e){ 7 mOnTestListening=e; 8 }
2.为了监听的实现,我们需要监听到的信息进行扫描,这时我们就用到了定时器,它能够按一定时间执行一次Handler;
1 Timer mTimer=new Timer(); 2 TimerTask task=new TimerTask(){ 3 4 @Override 5 public void run() { 6 // TODO Auto-generated method stub 7 Message message = new Message(); 8 9 handler.sendMessage(message); 10 11 } 12 13 }; 14 Handler handler=new Handler(){ 15 16 @Override 17 public void handleMessage(Message msg) { 18 // TODO Auto-generated method stub 19 if(mOnTestListening!=null){ 20 mOnTestListening.TestListening(0); 21 } 22 23 super.handleMessage(msg); 24 } 25 26 };
3.在类中定义一个共有函数run(),用于启动类中的定时器;
1 public void run(){ 2 mTimer.schedule(task, 5000,5000);//每五秒执行一次handler 3 }
全部源代码:
监听类TestA:
package ccit.qrs101; import java.util.Timer; import java.util.TimerTask; import android.os.Handler; import android.os.Message; public class testA { Timer mTimer=new Timer(); TimerTask task=new TimerTask(){ @Override public void run() { // TODO Auto-generated method stub Message message = new Message(); handler.sendMessage(message); } }; Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(mOnTestListening!=null){ mOnTestListening.TestListening(0); } super.handleMessage(msg); } }; public void run(){ mTimer.schedule(task, 5000,5000);//每五秒执行一次handler } public interface OnTestListening{ void TestListening(int i); } OnTestListening mOnTestListening=null; public void setOnTestListening(OnTestListening e){ mOnTestListening=e; } }
Activity:
package ccit.qrs101; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class TestActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); testA mtestA=new testA(); mtestA.run(); mtestA.setOnTestListening(new testA.OnTestListening() { @Override public void TestListening(int i) { // TODO Auto-generated method stub //Toast.makeText(TestActivity.this, "监听成功!!!", 1000).show(); new AlertDialog.Builder(TestActivity.this) .setTitle("信息提示") .setMessage("监听成功!!!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }) .create() .show(); } }); } }