Я хочу обнаружить входящий телефонный звонок и узнать номер телефона. Я также хочу знать, когда вызов закончен.
Я нашел этот код здесь: { ссылка }
Он отлично работает в начале, но после некоторых звонков я не больше не получает ответа от класса.
Кто-нибудь может мне помочь с этим? Заранее спасибо!
PhoneCallListener
public class PhoneCallListener extends PhoneStateListener {
private static final String LOG_TAG = PhoneCallListener.class.getSimpleName();
private boolean isPhoneCalling = false;
private Context context;
PhoneCallListener(Context context) {
this.context = context;
Log.d(LOG_TAG, "PhoneCallListener initiated");
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.d(LOG_TAG, "onCallStateChange " + state);
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE number");
if (isPhoneCalling) {
Handler handler = new Handler();
//Put in delay because call log is not updated immediately when state changed
// The dialler takes a little bit of time to write to it 500ms seems to be enough
handler.postDelayed(new Runnable() {
@Override
public void run() {
// get start of cursor
Log.i("CallLogDetailsActivity", "Getting Log activity...");
String[] projection = new String[]{CallLog.Calls.NUMBER};
@SuppressLint("MissingPermission") Cursor cur = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls.DATE + " desc");
if (cur != null) {
cur.moveToFirst();
String lastCallnumber = cur.getString(0);
Log.d(LOG_TAG, "Call ended: " + lastCallnumber);
cur.close();
}
}
}, 500);
isPhoneCalling = false;
}
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private TextView tv;
private Receiver phoneReceiver, smsReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
PhoneCallListener phoneListener = new PhoneCallListener(this);
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
}