不允许Broadcastreceiver组件与服务结合



我正在尝试实现收到电话时调用的广播。在Broadcastreceiver中,我试图从联系人的电话号码中获取联系人的名称,然后初始化叙述特定消息的TextTospeech对象。

我遇到了错误。因此,我该怎么做才能实现所需的功能。这是下面的代码

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;
    }
}
}

在您的应用程序中创建一个Service(它需要是前景服务),该服务由您的BroadcastReceiver启动以完成工作。在您的服务中,您将能够查询联系人并将文本触发到语音。

相关内容

  • 没有找到相关文章

最新更新