Android 教程 使用Service
2010-05-06 16:23:00 来源:WEB开发网_nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
像这样,我在Service的几个生命周期函数中加了打印log的语句,方便测试。
Java代码
public class LocalBinder extends Binder {
TestService getService() {
return TestService.this;
}
}
这个方法是为了让调用者得到这个Service并操作它。
Service本身就这样简单了,你需要做什么就在onCreate和onStart里做好了,起个线程什么的。
再看一下它的调用者,TestServiceHolder
Java代码
package com.haric.tutorial;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestServiceHolder extends Activity {
private boolean _isBound;
private TestService _boundService;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_service_holder);
setTitle(”Service Test”);
initButtons();
}
private ServiceConnection _connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
_boundService = ((TestService.LocalBinder)service).getService();
Toast.makeText(TestServiceHolder.this, “Service connected”,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// unexpectedly disconnected,we should never see this happen.
更多精彩
赞助商链接