Android 编写 Service 入门
2010-04-09 06:15:00 来源:WEB开发网这是新建立的接口代码:
package com.easymorse;
public interface ICountService {
public abstract int getCount();
}
修改后的CountService代码:
package com.easymorse;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class CountService extends Service implements ICountService {
private boolean threadDisable;
private int count;
private ServiceBinder serviceBinder=new ServiceBinder();
public class ServiceBinder extends Binder implements ICountService{
@Override
public int getCount() {
return count;
}
}
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onCreate() {
super.onCreate();
new Thread(new Runnable() {
@Override
public void run() {
while (!threadDisable) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
Log.v("CountService", "Count is " + count);
}
}
}).start();
}
@Override
public void onDestroy() {
super.onDestroy();
this.threadDisable = true;
Log.v("CountService", "on destroy");
}
/* (non-Javadoc)
* @see com.easymorse.ICountService#getCount()
*/
public int getCount() {
return count;
}
}
服务的注册也要做改动,AndroidManifest.xml文件:
更多精彩
赞助商链接