我想在状态栏中显示其他应用程序发布的通知。所以我做了一个按钮。单击该按钮将调用executeButtonClick()
方法。 我的代码:
public void executeButtonClick(View view) {
NLService nlService = new NLService();
if(nlService.getActiveNotifications()!=null) {
Toast.makeText(MainActivity.this,"InsideIf",Toast.LENGTH_SHORT).show();
for (StatusBarNotification sbn : nlService.getActiveNotifications()) {
String temp = "Package Name: " + sbn.getPackageName() +
"\n" + "Title: " + sbn.getNotification().extras.getString("android.title") + "\n" +
"Text: " + sbn.getNotification().extras.getCharSequence("android.text");
String newText = textView.getText().toString() + temp;
textView.setText(newText);
}
}
}
但是未显示通知,并且我得到了空指针异常:
"Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference"
在以下行中:activity.executeButtonClick(com.example.asus.notificationtest.MainActivity.textView);
onNotificationPosted()
方法的:
public class NLService extends NotificationListenerService {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if(MainActivity.textView != null)
activity.executeButtonClick(com.example.asus.notificationtest.MainActivity.textView);
//Toast.makeText(this,"Post from: "+sbn.getPackageName(),Toast.LENGTH_SHORT).show();
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
//Toast.makeText(this,"Post from: "+sbn.getPackageName(),Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:0)
要使Notification侦听器服务正常运行,有许多步骤?是否完全检测到通知?
步骤: 1)在清单中请求权限(例如):
<service android:name=".TheNotificationListener"
android:label="NotifiationListener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
2)向用户请求运行时权限:
private void assessPermissions() {
if(isPermissionRequired()){
requestNotificationPermission();
}else{
startBackground();
}
}
public boolean isPermissionRequired() {
ComponentName cn = new ComponentName(this, TheNotificationListener.class);
String flat = Settings.Secure.getString(this.getContentResolver(), "enabled_notification_listeners");
final boolean enabled = flat != null && flat.contains(cn.flattenToString());
return !enabled;
}
private void requestNotificationPermission() {
Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivityForResult(intent, 101);
}
提示:确保从通知侦听器服务中删除绑定操作!我花了一天的时间才弄清楚我不应该在那儿放那个代码。