如何在Android设备中检测来电?


130

我正在尝试制作一个类似的应用程序,当电话打来时,我想检测该号码。以下是我尝试过的方法,但未检测到来电。

我想MainActivity在后台运行我,该怎么办?

我已经在manifest文件中给予了许可。

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

清单中还应该提供其他内容吗?

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);
   }

   public class myPhoneStateChangeListener extends PhoneStateListener {
       @Override
       public void onCallStateChanged(int state, String incomingNumber) {
           super.onCallStateChanged(state, incomingNumber);
           if (state == TelephonyManager.CALL_STATE_RINGING) {
               String phoneNumber =   incomingNumber;
           }
       }
   }
}

我们应该为Android P做些什么
艾哈迈德·阿斯兰

Answers:


336

这是我用来执行此操作的方法:

表现:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

<!--This part is inside the application-->
    <receiver android:name=".CallReceiver" >
        <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>

我的基础可重用呼叫检测器

package com.gabesechan.android.reusable.receivers;

import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

public abstract class PhonecallReceiver extends BroadcastReceiver {

    //The receiver will be recreated whenever android feels like it.  We need a static variable to remember data between instantiations

    private static int lastState = TelephonyManager.CALL_STATE_IDLE;
    private static Date callStartTime;
    private static boolean isIncoming;
    private static String savedNumber;  //because the passed incoming is only valid in ringing


    @Override
    public void onReceive(Context context, Intent intent) {

        //We listen to two intents.  The new outgoing call only tells us of an outgoing call.  We use it to get the number.
        if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
            savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
        }
        else{
            String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
            String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            int state = 0;
            if(stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                state = TelephonyManager.CALL_STATE_IDLE;
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            }
            else if(stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                state = TelephonyManager.CALL_STATE_RINGING;
            }


            onCallStateChanged(context, state, number);
        }
    }

    //Derived classes should override these to respond to specific events of interest
    protected abstract void onIncomingCallReceived(Context ctx, String number, Date start);
    protected abstract void onIncomingCallAnswered(Context ctx, String number, Date start);
    protected abstract void onIncomingCallEnded(Context ctx, String number, Date start, Date end);

    protected abstract void onOutgoingCallStarted(Context ctx, String number, Date start);      
    protected abstract void onOutgoingCallEnded(Context ctx, String number, Date start, Date end);

    protected abstract void onMissedCall(Context ctx, String number, Date start);

    //Deals with actual events

    //Incoming call-  goes from IDLE to RINGING when it rings, to OFFHOOK when it's answered, to IDLE when its hung up
    //Outgoing call-  goes from IDLE to OFFHOOK when it dials out, to IDLE when hung up
    public void onCallStateChanged(Context context, int state, String number) {
        if(lastState == state){
            //No change, debounce extras
            return;
        }
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                isIncoming = true;
                callStartTime = new Date();
                savedNumber = number;
                onIncomingCallReceived(context, number, callStartTime);
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                //Transition of ringing->offhook are pickups of incoming calls.  Nothing done on them
                if(lastState != TelephonyManager.CALL_STATE_RINGING){
                    isIncoming = false;
                    callStartTime = new Date();
                    onOutgoingCallStarted(context, savedNumber, callStartTime);                     
                }
                else
                {
                    isIncoming = true;
                    callStartTime = new Date();
                    onIncomingCallAnswered(context, savedNumber, callStartTime); 
                }

                break;
            case TelephonyManager.CALL_STATE_IDLE:
                //Went to idle-  this is the end of a call.  What type depends on previous state(s)
                if(lastState == TelephonyManager.CALL_STATE_RINGING){
                    //Ring but no pickup-  a miss
                    onMissedCall(context, savedNumber, callStartTime);
                }
                else if(isIncoming){
                    onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
                }
                else{
                    onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
                }
                break;
        }
        lastState = state;
    }
}

然后使用它,只需从它派生一个类并实现一些简单的函数即可,无论您关心哪种调用类型:

public class CallReceiver extends PhonecallReceiver {

    @Override
    protected void onIncomingCallReceived(Context ctx, String number, Date start)
    {
        //
    }

    @Override
    protected void onIncomingCallAnswered(Context ctx, String number, Date start)
    {
        //
    }

    @Override
    protected void onIncomingCallEnded(Context ctx, String number, Date start, Date end)
    {
        //
    }

    @Override
    protected void onOutgoingCallStarted(Context ctx, String number, Date start)
    {
        //
    } 

    @Override 
    protected void onOutgoingCallEnded(Context ctx, String number, Date start, Date end)
    {
        //
    }

    @Override
    protected void onMissedCall(Context ctx, String number, Date start)
    {
        //
    }

}

另外,您可以在我的博客上看到我写过一篇关于代码为何如此的文章。要点链接:https : //gist.github.com/ftvs/e61ccb039f511eb288ee

编辑:更新为更简单的代码,因为我已经重新编写了该类供自己使用


2
此代码不显示任何内容。它的作用是在拨出电话开始/结束时给您打电话,并向您传递号码,开始时间和结束时间。实际显示它是您的工作,因为我无法知道您希望如何完成它。
Gabe Sechan 2014年

3
@GabeSechan:太棒了!您能指导我处理呼叫等待情况吗?
Mehul Joisar 2014年

6
只是要补充一点,当应用程序不在前台或后台时,它才起作用,直到我在接收器中添加了它:“ android:enabled =” true“
Rajat Sharma 2014年

1
静态变量将一直存在,直到应用程序被踢出内存为止(这可能要花很长的时间,具体取决于服务是否正在运行以及一般的电话内存状况)。但是,是的,它们可能会丢失。您可以通过共享首选项将其写入磁盘,但这也可能导致错误的结果-在某些情况下(例如在电话重启后),您将无法正确清除数据。就我的用例而言,罕见的null和丢失数据要比错误数据要好。随意根据您的需求进行调整。
Gabe Sechan 2015年

1
@GabeSechan:似乎有一个错误。lastState 不应初始化为CALL_STATE_IDLE。在当前状态为时,我的应用程序被杀死时,我错过了几个电话RINGING。因为当它IDLE在调用结束时再次变为静态变量时,它会被初始化为,CALL_STATE_IDLE并且不执行任何操作会反跳。因此我们失去了对的参考lastState
海森堡

23
private MyPhoneStateListener phoneStateListener = new MyPhoneStateListener();

注册

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

并注销

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

我应该在mainactivity中使用它吗?
Jesbin MJ

将此放置在您要监听更改的类中。.通常在oncreate中完成注册,在ondestroy中取消注册..在类中全局声明对象
stinepike

此选项不需要权限。
迈克

尽管Gabe的解决方案更适合于更具侵入性的功能(例如Viber之类的应用程序),但对于那些只需要对接听电话的用户行为做出反应的人来说,这是最佳的解决方案。在这种情况下,请求运行时许可很可能是一种过大的做法,并且可能不会被用户很好接受。
bosphere

1
我想做些什么,当有来电时,如何处理这段代码?
Noor Hossain

14

使用Android P-Api级别28: 您需要获得READ_CALL_LOG权限

限制访问通话记录

Android的P移动CALL_LOGREAD_CALL_LOGWRITE_CALL_LOG,和PROCESS_OUTGOING_CALLS从权限PHONE权限组新的CALL_LOG权限组。该组使用户可以更好地控制和查看需要访问有关电话敏感信息的应用程序,例如读取电话记录和识别电话号码。

要从PHONE_STATE意向操作中读取数字,您需要READ_CALL_LOG权限和READ_PHONE_STATE权限。要从中读取数字onCallStateChanged(),您现在READ_CALL_LOG仅需要许可。您不再需要READ_PHONE_STATE许可。


对于那些谁只添加READ_CALL_LOGAndroidManifest.xml专注于增加在许可请求MainActivity
Piyush

13

更新:除非您明确要求用户授予必要的权限,否则Gabe Sechan发布的真棒代码将不再起作用。您可以在主要活动中放置以下代码来请求这些权限:

    if (getApplicationContext().checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission has not been granted, therefore prompt the user to grant permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_PHONE_STATE},
                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
    }

    if (getApplicationContext().checkSelfPermission(Manifest.permission.PROCESS_OUTGOING_CALLS)
            != PackageManager.PERMISSION_GRANTED) {
        // Permission has not been granted, therefore prompt the user to grant permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.PROCESS_OUTGOING_CALLS},
                MY_PERMISSIONS_REQUEST_PROCESS_OUTGOING_CALLS);
    }

还:正如某人在Gabe的帖子下方的评论中提到的那样,您必须向android:enabled="true接收方添加一些代码段,以便在应用程序当前未在前台运行时检测传入的呼叫:

    <!--This part is inside the application-->
    <receiver android:name=".CallReceiver" android:enabled="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>

如果应用程序没有任何活动,而只有广播接收器和服务,该怎么办?然后,我们应该在哪里编写此代码以从用户那里获得许可,因为除非给出此许可,否则不会调用broadcastreceiver。
user2779311 '18

2
即使它仅打开一次,您也至少需要一个MainActivity。以我的呼叫阻止应用程序RoboStop为例:当用户首次下载该应用程序,然后单击该应用程序图标以启动该应用程序时,系统将提示他们授予我的应用程序必要的权限。该应用程序还具有一个启用/禁用呼叫阻止的按钮,但是用户不需要再次启动该应用程序/活动,该呼叫阻止将在后台进行,而无需用户再次启动该应用程序/活动。
topherPedersen

那些谁拥有实现这个麻烦,请按照本教程studytutorial.in/...
Prasath

5

这可能对您有帮助,也可能会增加要求

public class PhoneListener extends PhoneStateListener
{
    private Context context;
    public static String getincomno;

    public PhoneListener(Context c) {
        Log.i("CallRecorder", "PhoneListener constructor");
        context = c;
    }

    public void onCallStateChanged (int state, String incomingNumber)
    {

        if(!TextUtils.isEmpty(incomingNumber)){
        // here for Outgoing number make null to get incoming number
        CallBroadcastReceiver.numberToCall = null;
        getincomno = incomingNumber;
        }

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:

            break;
        case TelephonyManager.CALL_STATE_RINGING:
            Log.d("CallRecorder", "CALL_STATE_RINGING");
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:

            break;
        }
    }
}

2
这似乎很好。但是如何从活动中使用它?请告诉我细节
阿米尔(Amir)2015年


2

这是一种可以避免使用PhonestateListener和其他并发症的简单方法。
所以我们在这里接受3个事件在Android,如RINGINGOFFHOOKIDLE。而为了获得呼叫的所有可能的状态,我们需要定义我们自己的国家一样RINGINGOFFHOOKIDLEFIRST_CALL_RINGINGSECOND_CALL_RINGING。它可以处理电话中的每个状态。
请考虑以某种方式,我们从android接收事件,我们将定义我们的待命状态。参见代码。

public class CallListening  extends BroadcastReceiver {
    private static final String TAG ="broadcast_intent";
    public static String incoming_number;
    private String current_state,previus_state,event;
    public static Boolean dialog= false;
    private Context context;
    private SharedPreferences sp,sp1;
    private SharedPreferences.Editor spEditor,spEditor1;
    public void onReceive(Context context, Intent intent) {
        //Log.d("intent_log", "Intent" + intent);
        dialog=true;
        this.context = context;
        event = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        incoming_number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.d(TAG, "The received event : "+event+", incoming_number : " + incoming_number);
        previus_state = getCallState(context);
        current_state = "IDLE";
        if(incoming_number!=null){
            updateIncomingNumber(incoming_number,context);
        }else {
            incoming_number=getIncomingNumber(context);
        }
        switch (event) {
            case "RINGING":
                Log.d(TAG, "State : Ringing, incoming_number : " + incoming_number);
            if((previus_state.equals("IDLE")) || (previus_state.equals("FIRST_CALL_RINGING"))){
                    current_state ="FIRST_CALL_RINGING";
                }
                if((previus_state.equals("OFFHOOK"))||(previus_state.equals("SECOND_CALL_RINGING"))){
                    current_state = "SECOND_CALL_RINGING";
                }

                break;
            case "OFFHOOK":
                Log.d(TAG, "State : offhook, incoming_number : " + incoming_number);
                if((previus_state.equals("IDLE")) ||(previus_state.equals("FIRST_CALL_RINGING")) || previus_state.equals("OFFHOOK")){
                    current_state = "OFFHOOK";
                }
                if(previus_state.equals("SECOND_CALL_RINGING")){
                    current_state ="OFFHOOK";
                    startDialog(context);
                }
                break;
            case "IDLE":
                Log.d(TAG, "State : idle and  incoming_number : " + incoming_number);
                if((previus_state.equals("OFFHOOK")) || (previus_state.equals("SECOND_CALL_RINGING")) || (previus_state.equals("IDLE"))){
                    current_state="IDLE";
                }
                if(previus_state.equals("FIRST_CALL_RINGING")){
                    current_state = "IDLE";
                    startDialog(context);
                }
                updateIncomingNumber("no_number",context);
                Log.d(TAG,"stored incoming number flushed");
                break;
        }
        if(!current_state.equals(previus_state)){
            Log.d(TAG, "Updating  state from "+previus_state +" to "+current_state);
            updateCallState(current_state,context);

        }
    }
    public void startDialog(Context context) {
        Log.d(TAG,"Starting Dialog box");
        Intent intent1 = new Intent(context, NotifyHangup.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);

    }
    public void updateCallState(String state,Context context){
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        spEditor = sp.edit();
        spEditor.putString("call_state", state);
        spEditor.commit();
        Log.d(TAG, "state updated");

    }
    public void updateIncomingNumber(String inc_num,Context context){
        sp = PreferenceManager.getDefaultSharedPreferences(context);
        spEditor = sp.edit();
        spEditor.putString("inc_num", inc_num);
        spEditor.commit();
        Log.d(TAG, "incoming number updated");
    }
    public String getCallState(Context context){
        sp1 = PreferenceManager.getDefaultSharedPreferences(context);
        String st =sp1.getString("call_state", "IDLE");
        Log.d(TAG,"get previous state as :"+st);
        return st;
    }
    public String getIncomingNumber(Context context){
        sp1 = PreferenceManager.getDefaultSharedPreferences(context);
        String st =sp1.getString("inc_num", "no_num");
        Log.d(TAG,"get incoming number as :"+st);
        return st;
    }
}

0

@Gabe Sechan,感谢您的代码。除了以外,它都可以正常工作onOutgoingCallEnded()。它永远不会执行。测试手机为三星S5和Trendy。我认为有2个错误。

1:缺少一对方括号。

case TelephonyManager.CALL_STATE_IDLE: 
    // Went to idle-  this is the end of a call.  What type depends on previous state(s)
    if (lastState == TelephonyManager.CALL_STATE_RINGING) {
        // Ring but no pickup-  a miss
        onMissedCall(context, savedNumber, callStartTime);
    } else {
        // this one is missing
        if(isIncoming){
            onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
        } else {
            onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
        }
    }
    // this one is missing
    break;

2:如果位于函数末尾,lastState则不会更新state。应将其替换为该函数的第一行,方法是

public void onCallStateChanged(Context context, int state, String number) {
    int lastStateTemp = lastState;
    lastState = state;
    // todo replace all the "lastState" by lastStateTemp from here.
    if (lastStateTemp  == state) {
        //No change, debounce extras
        return;
    }
    //....
}

我已按照您的建议添加了其他内容,lastStatesavedNumber加入了共享的首选项。

刚刚测试了上面的更改。错误至少在我的手机上修复。


0

请使用以下代码。它将帮助您获取带有其他呼叫详细信息的来电号码。

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/call"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

private static final int MISSED_CALL_TYPE = 0;
private TextView txtcall;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtcall = (TextView) findViewById(R.id.call);

    StringBuffer sb = new StringBuffer();
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
            null, null, null);
    int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
    sb.append("Call Details :");
    while (managedCursor.moveToNext()) {
        String phNumber = managedCursor.getString(number);
        String callType = managedCursor.getString(type);
        String callDate = managedCursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = managedCursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {

        case CallLog.Calls.OUTGOING_TYPE:
            dir = "OUTGOING";
            break;

        case CallLog.Calls.INCOMING_TYPE:
            dir = "INCOMING";
            break;

        case CallLog.Calls.MISSED_TYPE:
            dir = "MISSED";
            break;
        }
        sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                + dir + " \nCall Date:--- " + callDayTime
                + " \nCall duration in sec :--- " + callDuration);
        sb.append("\n----------------------------------");
    }
    managedCursor.close();
    txtcall.setText(sb);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

} 

并在清单请求中请求以下权限:

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_LOGS"/>

READ_LOGS这样做是为了让您的应用禁止进入Play商店
Duna

0

您需要一个BroadcastReceiver,以便ACTION_PHONE_STATE_CHANGED在电话状态从空闲,振铃,摘机状态变化时都将呼叫您的已接收电话,因此从上一个值和新值中您可以检测到这是呼入还是呼出。

所需权限为:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

但是,如果您还想在该广播中接收EXTRA_INCOMING_NUMBER,则需要另一个权限:“ android.permission.READ_CALL_LOG”

和类似这样的代码:

val receiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d(TAG, "onReceive")
    }
}

override fun onResume() {
    val filter = IntentFilter()
    filter.addAction("android.intent.action.PHONE_STATE")
    registerReceiver(receiver, filter)
    super.onResume()
}

override fun onPause() {
    unregisterReceiver(receiver)
    super.onPause()
}

在接收器类中,我们可以通过读取如下意图获取当前状态:

intent.extras["state"]

额外的结果可能是:

响铃->如果您的电话正在响铃

OFFHOOK->如果您正在与某人交谈(来电或来电)

空闲->如果通话结束(来电或来电)

使用PHONE_STATE广播,我们无需使用PROCESS_OUTGOING_CALLS权限或已弃用的NEW_OUTGOING_CALL操作。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.