不允许BroadcastReceiver组件绑定到服务

问题描述 投票:0回答:1

我正在尝试实现在收到电话呼叫时调用的BroadcastReceiver。在BroadcastReceiver中,我试图从联系人的电话号码中获取联系人的姓名,然后初始化一个叙述特定消息的TextToSpeech对象。

我收到错误“android.content.ReceiverCallNotAllowedException:不允许BroadcastReceiver组件绑定到服务”。那么我该怎么做才能实现所需的功能。这是下面的代码

public class IncomingCall extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    try {
       // this.context = context;
        // TELEPHONY MANAGER class object to register one listner
        TelephonyManager tmgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);

        //Create Listner
        MyPhoneStateListener PhoneListener = new MyPhoneStateListener(context);

        // Register listener for LISTEN_CALL_STATE
        tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

    } catch (Exception e) {
        Log.e("Phone Receive Error", " " + e);
    }

}
private class MyPhoneStateListener extends PhoneStateListener {
    Context context;
    TextToSpeech ttobj;
    MyPhoneStateListener(Context context)
    {
        this.context = context;
        ttobj = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                ttobj.setLanguage(Locale.UK);
            }
        });
    }

    public void onCallStateChanged(int state, String incomingNumber) {

        Log.d("MyPhoneListener",state+"   incoming no:"+incomingNumber);

        if (state == 1) {
           // String msg = "New Phone Call Event. Incomming Number : "+incomingNumber;
            String name = getContactName(incomingNumber,context);
            String msg="";
            if(name=="")
                name = "Unknown Number";
            msg = "Sir, Incoming Call from "+name ;
            ttobj.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    public String getContactName(final String phoneNumber, Context context)
    {
        Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));

        String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

        String contactName="";
        Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);

        if (cursor != null) {
            if(cursor.moveToFirst()) {
                contactName=cursor.getString(0);
            }
            cursor.close();
        }

        return contactName;
    }
}
}
android broadcastreceiver text-to-speech
1个回答
1
投票

在你的应用程序中创建一个Service(它需要是一个前台服务),由你的BroadcastReceiver开始做这项工作。在您的服务中,您将能够查询联系人并触发文本到语音。

© www.soinside.com 2019 - 2024. All rights reserved.