package s.d;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
/**
* @version 2012-7-19 下午05:14:12
**/
public class mainService extends Service {
myBinder binder;
// 如果使用绑定必须有Binder子类
class myBinder extends Binder {
mainService getService() {
return mainService.this;
}
}
// 当service被绑定了则不能调用stopservice停止服务
// 实例被绑定后不会调用onStart
// 绑定
@Override
public IBinder onBind(Intent intent) {
Log.e("mainService", "onBind");
return binder;
}
// 创建服务
@Override
public void onCreate() {
binder = new myBinder();
Log.e("mainService", "onCreate");
// 提高服务优先级减少被杀掉的几率
setForeground(true);
// 取消提高服务优先级减少被杀掉的几率
stopForeground(true);
// 把他显示在状态栏 不会用
// startForeground(id, notification)
super.onCreate();
}
// 开始服务 可以执行多次
@Override
public void onStart(Intent intent, int startId) {
Log.e("mainService", "onStart");
super.onStart(intent, startId);
}
// 销毁
@Override
public void onDestroy() {
Log.e("mainService", "onDestroy");
super.onDestroy();
}
// 重新绑定
@Override
public void onRebind(Intent intent) {
Log.e("mainService", "onRebind");
super.onRebind(intent);
}
// 解绑
@Override
public boolean onUnbind(Intent intent) {
Log.e("mainService", "onUnbind");
return super.onUnbind(intent);
}
}
package s.d;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
//需在Manifest.xml中注册
public class mainActivity extends Activity {
Button b1;
Button b2;
mainService binder = null;
// 实现绑定需要ServiceConnection
ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
binder = null;
Log.e("onServiceDisconnected", "" + name);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = ((mainService.myBinder) (service)).getService();
if(binder != null) {
}
Log.e("onServiceConnected", "" + name);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.btn1);
b2 = (Button) findViewById(R.id.btn2);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(mainActivity.this, mainService.class));
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(mainActivity.this, mainService.class));
}
});
// 绑定服务
bindService(new Intent(mainActivity.this, mainService.class), sc,
BIND_AUTO_CREATE);
}
// 绑定后需写解绑方法
@Override
protected void onDestroy() {
super.onDestroy();
// 解绑
unbindService(sc);
}
}