我正在开发一个应用程序,如果有来电,我需要从onResume完成活动。我创建了一个CallHelper类,在其中我使用PhoneStateListener检测任何传入呼叫。
public class CallHelper {
/**
* Listener to detect incoming calls.
*/
private static class CallStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
System.out.println("RINGING");
OverlayActivity overlayActivity = OverlayActivity.getInstance();
overlayActivity.finish();
System.out.println("Activity has been closed!!");
break;
}
}
}
/**
* Broadcast receiver to detect the outgoing calls.
*/
public class OutgoingReceiver extends BroadcastReceiver {
public OutgoingReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(ctx,
"Outgoing: "+number,
Toast.LENGTH_LONG).show();
}
}
private Context ctx;
private TelephonyManager tm;
private CallStateListener callStateListener;
private OutgoingReceiver outgoingReceiver;
public CallHelper(Context ctx) {
this.ctx = ctx;
callStateListener = new CallStateListener();
outgoingReceiver = new OutgoingReceiver();
}
/**
* Start calls detection.
*/
public void start() {
tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
ctx.registerReceiver(outgoingReceiver, intentFilter);
}
/**
* Stop calls detection.
*/
public void stop() {
tm.listen(callStateListener, PhoneStateListener.LISTEN_NONE);
ctx.unregisterReceiver(outgoingReceiver);
}
}
我需要检测onResume内部,如果有任何调用,我需要完成活动,如果没有,我什么都不需要做。
我还没有找到解决方案,所以我在我的活动的onResume中添加了检测CallStateChange的代码,并使用该代码执行我想在CallStateChange上执行的任务。
我不确定这是否是一个正确的解决方案,但我希望社会各界对此发表意见。
这是我正在使用的代码:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber)
{
if(state==TelephonyManager.CALL_STATE_RINGING){
// Code i wanted to execute
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);