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;之后的所有联系号码。使用的方法,但是当我开始意图发生时......
我的问题是什么? :/
答案 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);