我想检测拨出电话何时开始和结束,并想在通话开始时启动服务并在通话结束时结束服务。
这是我从另一个问题中得到的代码,但不知道在哪里放置启动和停止活动以使其工作。
public class CallListener {
private CallStateListener callStateListener = null;
private OutgoingReceiver outgoingReceiver = null;
public CallListener(Context context) {
this.context = context;
callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
}
private class CallStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
doSomething1();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
doSomething2();
break;
case TelephonyManager.CALL_STATE_RINGING:
doSomething3();
break;
}
}
}
public class OutgoingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
doSomething4();
}
}
public void start() {
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
context.registerReceiver(outgoingReceiver, intentFilter);
}
public void stop() {
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
context.unregisterReceiver(outgoingReceiver);
}}
这是添加服务以使其工作:
public class MyService extends Service {
private CallListener call = null;
public MyService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
call = new CallListener(getApplicationContext());
call.start();
return(START_STICKY);
}
@Override
public void onDestroy() {
call.stop();
call.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
非常感谢您的帮助,我可能知道这很容易,但我只是不知道。
谢谢,祝你有美好的一天..!! :)