关闭应用程序时检测来电和去电

时间:2018-07-06 06:25:16

标签: android telephonymanager

我一直在开发一个可以检测android中的传入和传出呼叫并记录它们的应用程序。我需要知道哪个模拟用户接听电话或拨打电话。

我可以检测到电话,但在双卡情况下无法检测到我的电话号码。我已经尝试从通话记录中检查它。

这是我的代码:

*

还尝试检测是否使用检测卡槽

private void fetchCallLogs(final Context context) {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            // get start of cursor
            Log.i("CallLogDetailsActivity", "Getting Log activity...");

            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Cursor cur = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " desc");

            int accountId = cur.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID);
            //Check if call was made from sim 1 or sim 2 , if it returns 0 its from sim 1 else if 1 its from sim 2.

            String callid = "0";
            if (cur.moveToFirst() == true) {
                String phNumber = cur.getString(accountId);
                int idSimId = getSimIdColumn(cur);

                if(idSimId >= 0){
                    callid = cur.getString(idSimId);
                }

                cur.close();


            }
        }
    }, 1500);
}

public static int getSimIdColumn(final Cursor c) {

    for (String s : new String[] { "sim_id", "simid","simId","simSlot", "sub_id","slot","simnum","slotId","slot_id","slotIdx" }) {
        int id = c.getColumnIndex(s);
        if (id >= 0) {
            Log.d("TAG", "sim_id column found: " + s);
            return id;
        }
    }
    Log.d("TAG", "no sim_id column found");
    return -1;
}

但这不起作用。

我需要一个可以检测到SIM卡号或插槽的代码。

谢谢。

2 个答案:

答案 0 :(得分:0)

关闭应用时,BroadCastReceiver无法运行的原因很少。

  
      
  1. 某些手机不允许在oppo,小米,华为等后台运行应用程序。要解决此问题,请尝试Link
  2.   
  3. 最新的Android版本Oreo Broadcast Limitations
  4.   

如果这些原因不属于您的问题,请使用该服务。怎么做? click

答案 1 :(得分:0)

您应该在AndroidManifest.xml中隐式注册接收者,例如:

<receiver
    android:name=".PhonecallReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
    </intent-filter>
</receiver>