服务集成Service,通过Context.startService();或Context.bindService();
配置服务,<Service android:name="类名"/>
服务被调用时会调用onCreate()方法
onCreate(){
TelephonyManager telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(new TelListener(),PhoneStateListener.LISTEN_CALL_STATE);
}
private class TelListrener extends PhoneStateListener{
private String mobile;
public void onCallStateChanged(int state,String incomingNumber){//电话状态改变时调用
switch(state){
case TelephonyManager.CALL_STATE_IDLE://空闲
break;
case TelephonyManager.CALL_STATE_OFFHOOK://接电话
break;
case TelephonyManager.CALL_STATE_RINGING://ring~
break;
}
}
}
Context.startService()调用服务的onCreate()方法——>onStart()方法
多次调用只会多次调用onStart()方法,Context.stopService()会调用onDestroy();
Context.startService();不能与activity交互,Context.bindService();可以
private MyServiceConnection conn;
Context.bindService(intent,conn,BIND_AUTO_CREATE);
MyServiceConnection implements ServiceConnection{
public void onServiceConnected(ComponentName name, IBinder service) {//返回一个IBinder 对象
myservice = (IService)service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
myservice = null;
}
}