BroadcastReceiver用于来电

时间:2015-05-25 10:24:29

标签: android broadcastreceiver

在我的应用程序中,我希望在有来电时收到通知。为此我创建了一个BroadcastReceiver,它看起来像这样:

public void onReceive(Context context, Intent intent)
{
    MyPhoneStateListener phoneListener = new MyPhoneStateListener();

    TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    telephony.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}

private class MyPhoneStateListener extends PhoneStateListener
{
    public void onCallStateChanged(int state, String incomingNumber)
    {
        if(state == TelephonyManager.CALL_STATE_RINGING) incommingCall(incomingNumber);
        else if(state == TelephonyManager.CALL_STATE_IDLE) endingCall(incomingNumber);
    }

    //...
}

我现在的问题是这个接收器从未被调用过。我已经在Manifest中注册了这样的内容:

<receiver
    android:name="com.cilenco.interrupts.ContactControl"
    android:enabled="true"
    android:exported="false" >
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
 </receiver>

这有什么问题吗?或者这是一个接收器,我无法从Manifest注册?如果没有用户必须启动我的应用程序,您是否有其他想法如何实现?

2 个答案:

答案 0 :(得分:2)

android:exported="false"属性设为true

android:exported="true"

这样Android操作系统就可以将广播发送到您的应用程序,如果您指定导出为false,则Android操作系统将忽略您的应用程序。

答案 1 :(得分:-1)

    Try this one:



     public class Incomingcallreceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            // TODO Auto-generated method stub

      Do your stuff


        }

        }

在显示组中添加此项以注册呼叫接收器

     <receiver
            android:name="com.example.enwaye_connect.Incomingcallreceiver"
            android:label="Incomingcallreceiver" >
            <intent-filter>
                <action android:name="android.intent.action.PHONE_STATE" />
                 <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

同时添加权限

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" >
    </uses-permission>
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" >
    </uses-permission>
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.READ_LOGS" />