我已注册广播接收器以更改手机状态。 问题是我的接收器在拨打电话大约十次响铃后被激活。 我在AndroidManifest.xml中更改了接收器的优先级,但忽略了它。
我的收件人代码:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class PhoneStateReceiver extends BroadcastReceiver {
public static String caller_No = "";
public static boolean ringing = false;
@Override
public void onReceive(final Context context, Intent intent) {
try {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Log.d(General.TAG , "call ringing");
caller_No = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
ringing = true;
Toast.makeText(context, "Caller "+ caller_No , Toast.LENGTH_LONG).show();
DataSource db=new DataSource(context);
db.open();
if(db.IsNoExist(caller_No.replace("+98", "0")))
{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
acceptCall(context);
turnSpeakerOn(context);
}
},2000);
}
db.close();
}else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
//Call received
turnSpeakerOn(context);
Log.d(General.TAG , "call received");
}else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
//Call Dropped or rejected
ringing = false;
Log.d(General.TAG , "call dropped or rejected:"+caller_No);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void acceptCall(Context ctx) {
//setHeadSetConnectEmulated(ctx);
Intent buttonUP = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUP.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
ctx.sendOrderedBroadcast(buttonUP, "android.permission.CALL_PRIVILEGED");
}
private void turnSpeakerOn(Context ctx)
{
AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
}
}