在Android
中,经常用到的定时器主要有以下几种实现:
一、采用Handler与线程的sleep(long )方法
二、采用Handler的postDelayed(Runnable, long) 方法
三、采用Handler与timer及TimerTask结合的方法。
下面逐一介绍:
一、采用Handle与线程的sleep(long )方法
Handler主要用来处理接受到的消息。这只是最主要的方法,当然Handler里还有其他的方法供实现,有兴趣的可以去查API,这里不过多解释。
1.定义一个Handler类,用于处理接受到的Message.
Handler handler = new Handler() {
public void handleMessage(Message msg) {
//要做的事情
super.handleMessage(msg);
}
};
2.新建一个实现Runnable接口的线程类。如下:
public class MyThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);//线程暂停10秒,单位毫秒
Message message=new Message();
message.what=1;
handler.sendMessage(message);//发送消息
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
new Thread(new MyThread()).start();
4.启动线程后,线程每10s发送一次消息。
package com.quding.thread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.TextView; public class MyCounter extends Activity{ private TextView mTextView; private Handler handler; private int count; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mycounter); mTextView = (TextView) findViewById(R.id.mycounter_textView); handler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1){ //添加要干的事情 count++; mTextView.setText(count + ""); } } }; new Thread(new MyThread()).start(); Log.e("tag", "cehsi"); } public class MyThread implements Runnable{ public void run() { while(true){ try { Message message = new Message(); message.what = 1; Thread.sleep(1000); //间隔时间在这里定 //通过handler把这个线程的线程体放到主线程的消息队列中,使得该线程在主线程中执行 handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } } } }
二、采用Handler的postDelayed(Runnable, long) 方法
这个实现比较简单一些:
1. Handler handler=new Handler();
Runnable runnable=new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
//要做的事情
handler.postDelayed(this, 2000);
}
};
2.启动计时器:
handler.postDelayed(runnable, 2000);//每两秒执行一次runnable.
3.停止计时器:
handler.removeCallbacks(runnable);
package com.quding.thread; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.TextView; public class MyCounter extends Activity{ private TextView mTextView; private Handler handler; private int count; private Runnable myRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mycounter); mTextView = (TextView) findViewById(R.id.mycounter_textView); handler = new Handler(Looper.getMainLooper()); myRunnable = new Runnable(){ @Override public void run() { //此处添加每个一段时间要执行的语句 count++; mTextView.setText(count + ""); handler.postDelayed(this, 1000); } }; //启动计时器 handler.postDelayed(myRunnable, 1000); } @Override protected void onStop() { super.onStop(); handler.removeCallbacks(myRunnable); } }
三、采用Handler与timer及TimerTask结合的方法。
1.定义定时器、定时器任务及Handler句柄
private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//要做的事情
super.handleMessage(msg);
}
};
2.初始化计时器任务。
task = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
3.启动定时器
timer.schedule(task, 2000, 2000);
简要说一下上面三步提到的一些内容。
1.定时器任务(TimerTask)顾名思义,就是说当定时器到达指定的时间时要做的工作,这里是想Handler发送一个消息,由Handler类进行处理。
2. java.util.Timer.schedule(TimerTask task, long delay):这个方法是说,dalay/1000秒后执行task.只执行一次。
java.util.Timer.schedule(TimerTask
task, long delay, long
period):这个方法是说,delay/1000秒后执行task,然后进过period/1000秒再次执行task,这个用于循环任务,执行无数
次,当然,你可以用timer.cancel();取消计时器的执行。
package com.quding.thread; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.TextView; public class MyCounter extends Activity{ private TextView mTextView; private Handler handler; private int count; private Timer timer = new Timer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mycounter); mTextView = (TextView) findViewById(R.id.mycounter_textView); handler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1){ count++; mTextView.setText(count + ""); } } }; TimerTask task = new TimerTask() { @Override public void run() { Message msg =new Message(); msg.what = 1; handler.sendMessage(msg); } }; timer.schedule(task, 10000, 1000); // 第二个参数是定时开始计时,第三个参数是时间间隔 } }
嘿嘿,生活就是这样,你多么的努力,没人看到,但如果你不努力,那么你就更没人看到了
哈哈,说了些不必要的。在这里我把Hibernate 3.0 做个小小的例子
lib:
antlr-2.7.6.jar
commons-collections-3.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.12.0.GA.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.0.6-bin.jar
slf4j-api-1.6.1.jar
slf4j-api-1.6.2.jar
slf4j-ext-1.6.2.jar
slf4j-jcl-1.6.2.jar
slf4j-jdk14-1.6.2.jar
slf4j-log4j12-1.6.2.jar
slf4j-nop-1.6.2.jar
slf4j-simple-1.6.2.jar
package com.chenhailong; import java.io.Serializable; public class TUser implements Serializable { /** * */ private static final long serialVersionUID = -1886893835045076202L; private Integer id; private String name; public TUser() { } /** * @return the id */ public Integer getId() { return id; } /** * @param id * the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.chenhailong"> <class name="com.chenhailong.TUser" table="TUser"> <id name="id" column="id" type="java.lang.Integer"> <generator /> </id> <property name="name" column="name" type="java.lang.String" not-null="true" /> </class> </hibernate-mapping>
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"> <hibernate-configuration> <session-factory> <!-- properties --> <property name="connection.username">root</property> <property name="connection.url">JDBC:MySQL://localhost:3306/test</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.password">chenhailong</property> <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property> <!-- mapping files --> <mapping resource="com/chenhailong/TUser.hbm.xml" /> </session-factory> </hibernate-configuration>
/** * */ package com.chenhailong.main; import java.io.File; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.chenhailong.TUser; /** * @author chenhailong *上午10:09:22 *com.chenhailong.main */ public class Main { /** * Hibernate 3 dialect modify net.sf.hibernate -> org.hibernate */ public static void main(String[] args) { Session session = getSession(); //insertTUser(session); //selectTUser(session); deleteTUser(session); session.close(); } public static Session getSession() { Configuration cfg = new Configuration().configure(); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); return session; } public static Session getSession(String fileName) { File file = new File(fileName); Configuration cfg = new Configuration().configure(file); SessionFactory sessionFactory = cfg.buildSessionFactory(); Session session = sessionFactory.openSession(); return session; } public static void insertTUser(Session session) { Transaction tx = session.beginTransaction(); TUser t_user = new TUser(); t_user.setName("chenhailong"); session.save(t_user); session.flush(); tx.commit(); } @SuppressWarnings("unchecked") public static void selectTUser(Session session) { String hql = " from TUser where name='chenhailong'"; try { List<TUser> userList = session.createQuery(hql).list(); for (TUser user : userList) { int id = user.getId(); String name = user.getName(); System.out.println(id + "\t" + name); } } catch (Exception e) { e.printStackTrace(); } } public static void deleteTUser(Session session) { Transaction tx = session.beginTransaction(); TUser user = (TUser) session.get(TUser.class, new Integer(1)); session.delete(user); tx.commit(); } public static void deleteTUserUseHQL(Session session) { Transaction tx = session.beginTransaction(); session.delete("from TUser where id = 1"); tx.commit(); } public static void deleteTUseHQLByQuery(Session session) { String hql = "delete TUser where id = 1"; Query query = session.createQuery(hql); query.executeUpdate(); } }
1、下载Cygwin,只安装Devel
安装完通过gcc -v和make -v测试
用Ultraedit编辑\Cygwin\home\Adminstrator目录下的.bash_profile文件(不要用txt打开,会导致Cygwin报错),添加
NDK=/cygdrive/e/develop/android/android-NDK/android-ndk-1.5_r1
export NDK
重启Cygwin
2、下载android-ndk-r5
3、cd $NDK/samples/hello-jni
$NDK/ndk-build
当提示编译.so文件成功时,表示成功