import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
/**
* Created by BINGO on 2018/12/06.
*/
public class CallPhone {
TelephonyManager tm;
PhoneCallListener listener;
public void callA(Activity activity) {
try {
Intent call = new Intent(Intent.ACTION_CALL);
Uri data = Uri.parse("tel:" + "电话");
call.setData(data);
call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
listener = new PhoneCallListener(activity);
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
activity.startActivity(call);
} catch (Exception e) {
e.printStackTrace();
}
}
private class PhoneCallListener extends PhoneStateListener {
private boolean bphonecalling = false;
private Activity activity;
public PhoneCallListener(Activity activity) {
this.activity = activity;
}
@Override
public void onCallStateChanged(int state, String incomingnumber) {
// seems the incoming number is this call back always ""
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
bphonecalling = true;
} else if (TelephonyManager.CALL_STATE_IDLE == state && bphonecalling) {
if (tm != null) {
tm.listen(listener, PhoneStateListener.LISTEN_NONE);
}
bphonecalling = false;
Intent i = null;
i = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
activity.startActivity(i);
}
super.onCallStateChanged(state, incomingnumber);
}
}
}