在特定通知到达时拨打电话

时间:2015-05-21 16:14:12

标签: java android notifications call

当有特定的通知到达时,我试图拨打电话, 我使用Notification Service Listener来读取传入通知,

public void onNotificationPosted(StatusBarNotification sbn) {
    //  if(if this is my notificaion..){
    String name = sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TITLE));
    List<String> numbers = getPhoneNumbers(name);
    Log.d(TAG, "i have all this numbers - " + numbers.toString());

    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(Uri.parse("tel:" + numbers.get(1)));
    startActivity(intent);
}

&#34; getPhoneNumbers&#34;方法就是这个

public List<String> getPhoneNumbers(String name) {
    List<String> numbers = new ArrayList<String>();

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            "DISPLAY_NAME = '" + name + "'", null, null);
    if (cursor.moveToFirst()) {
        String contactId =
                cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
        //  Get all phone numbers.
                    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
        while (phones.moveToNext()) {
            String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
           numbers.add(number);

        }
        phones.close();
    }

    cursor.close();
    return numbers;

}

一切正常,(我使用断点来欺骗一切......) &#34;如果这是我的通知&#34;工作完美,我得到了sbn extras的名字,&#39;数字&#39; arraylist包括&#34; getPhoneNumbers&#34;之后的所有联系号码。使用的方法,但是当我开始意图发生时......

我的问题是什么? :/

2 个答案:

答案 0 :(得分:1)

让我们澄清一下:

<强>问题
调用onNotificationPosted时,startActivity(intent);方法无法启动电话。

<强>为什么
NotificationListenerService不是活动。

解决方案
MainActivity拨打startActivity(intent);

如何
activity中定义属性NotificationListenerService并定义接受活动的构造函数:

<强> NotificationListenerService.java

// define attribute activity:
MainActivity activity;

public NotificationListenerService(MainActivity activity) {
    this.activity = activity;
}

<强> MainActivity.java

// create a NotificationListenerService sending itself as reference
NotificationListenerService nls = new NotificationListenerService(this);

然后在onNotificationPosted内你会看到属性,所以你可以:

Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ numbers.get(1)));
activity.startActivity(intent);

答案 1 :(得分:0)

找到了一个从服务发起呼叫的解决方案:

Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + number));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
            startActivity(intent);

解决方案来自:Android: Make phone call from service