当屏幕被锁定时,您编写的代码将无法用于新设备,因为现在安卓会处理电池电量。因此,它不允许后台服务与接收器一起运行。但是,如果您想这样做,请遵循以下步骤:
-
步骤1)制作接收器
-
步骤2)启动onReceive方法上的服务/活动或任何任务
而不是作为接收者持续运行它来完成这项任务。
例如:
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
{
Bundle bb = intent.getExtras();
String state = bb.getString(TelephonyManager.EXTRA_STATE);
if ((state != null)&& (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)))
{
incommingNumber = bb.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
blockCall(context, bb);
}
}
public void blockCall(Context c, Bundle b)
{
TelephonyManager telephony = (TelephonyManager)
c.getSystemService(Context.TELEPHONY_SERVICE);
try {
Class cls = Class.forName(telephony.getClass().getName());
Method m = cls.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony);
//telephonyService.silenceRinger();
telephonyService.endCall();
new SendValue(c,incommingNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
其中SendValue(上下文c,字符串incomingNumber);是其他Java类的构造函数,用于在收到调用时执行必要的任务,incomingNumber是一个全局String变量,以便在收到调用后可以更改其值。