安卓 来电状态监听、去电监听
程序员文章站
2024-01-16 21:37:40
...
package sci.callshielder;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
/**
* 来电状态监听。
*
* <uses-permission android:name="android.permission.READ_PHONE_STATE" />
* */
abstract class CallInListener extends PhoneStateListener
{
TelephonyManager phoneManager;
public CallInListener(Context context)
{
phoneManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
Listen();
}
/** 监听来电状态 */
public void Listen()
{
phoneManager.listen(this, PhoneStateListener.LISTEN_CALL_STATE); // 在系统服务上,为当前Listener注册CALL_STATE状态监听
}
/** 不再监听 */
public void ClearListen()
{
phoneManager.listen(this, PhoneStateListener.LISTEN_NONE);
}
/** 重写监听来电状态 */
public void onCallStateChanged(int state, String incomingNumber)
{
if(state == TelephonyManager.CALL_STATE_IDLE) // 空闲/挂断
{
HungUp();
}
else if(state == TelephonyManager.CALL_STATE_RINGING) // 响铃
{
Ringing();
}
else if(state == TelephonyManager.CALL_STATE_OFFHOOK) // 接听
{
OffHook();
}
}
/** 响铃时执行逻辑 */
public abstract void Ringing();
/** 接听时执行逻辑 */
public abstract void OffHook();
/** 挂断时执行逻辑 */
public abstract void HungUp();
}
/**
* 去电监听。
*
* <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
* */
abstract class OutCallListener extends BroadcastReceiver
{
Context context;
public OutCallListener(Context context)
{
this.context = context;
Listen();
}
/** 监听来电状态 */
public void Listen()
{
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
context.registerReceiver(this, intentFilter);
}
/** 不再监听 */
public void ClearListen()
{
context.unregisterReceiver(this);
}
/** 重写监听去电事件 */
public void onReceive(Context context, Intent intent)
{
String phoneNumber = getResultData();
OutCall(phoneNumber);
}
/** 去电时执行逻辑 */
public abstract void OutCall(String phoneNumber);
}
/**
* PhoneServices.java: 服务逻辑暂未添加
* -----
* 2019-1-9 上午10:16:06
* scimence
*/
public class PhoneServices extends Service
{
public void onCreate()
{
CallInListener callin = new CallInListener(this)
{
@Override
public void Ringing()
{
// TODO Auto-generated method stub
}
@Override
public void OffHook()
{
// TODO Auto-generated method stub
}
@Override
public void HungUp()
{
// TODO Auto-generated method stub
}
};
OutCallListener callOut = new OutCallListener(this)
{
@Override
public void OutCall(String phoneNumber)
{
// TODO Auto-generated method stub
}
};
}
/* (non-Javadoc)
* @see android.app.Service#onBind(android.content.Intent)
*/
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
}
上一篇: ffmpeg处理视频命令
下一篇: curve分佈式系統在Linux上运行