2

我想通过使用NotificationListenerService来访问Android手机上的通知。我查了很多教程,但我找不到他们称之为服务的地方。如何在Android上启动NotificationListenerService

我应该在MainActivity上使用bindService还是startService?意图应该如何?有人能告诉我这个的语法吗?

退房服务实现我学习的一个:

public class NLService extends NotificationListenerService { 

Context context; 

@Override 
public void onCreate() { 

    super.onCreate(); 
    context = getApplicationContext(); 


} 


@Override 
public void onNotificationPosted(StatusBarNotification sbn) { 
    String pack = sbn.getPackageName(); 
    String ticker =""; 
    if(sbn.getNotification().tickerText !=null) { 
     ticker = sbn.getNotification().tickerText.toString(); 
    } 
    Bundle extras = sbn.getNotification().extras; 
    String title = extras.getString("android.title"); 
    String text = extras.getCharSequence("android.text").toString(); 
    int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON); 
    Bitmap id = sbn.getNotification().largeIcon; 


    Log.i("Package",pack); 
    Log.i("Ticker",ticker); 
    Log.i("Title",title); 
    Log.i("Text",text); 

    Intent msgrcv = new Intent("Msg"); 
    msgrcv.putExtra("package", pack); 
    msgrcv.putExtra("ticker", ticker); 
    msgrcv.putExtra("title", title); 
    msgrcv.putExtra("text", text); 
    if(id != null) { 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     //id.compress(Bitmap.CompressFormat.PNG, 100, stream); 
     byte[] byteArray = stream.toByteArray(); 
     msgrcv.putExtra("icon",byteArray); 
    } 
    LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv); 

} 
@Override 

public void onNotificationRemoved(StatusBarNotification sbn) { 
    Log.i("Msg","Notification Removed"); 

} 

}

+0

在这种情况下,你必须从android系统获得通知? – dipali

回答

3

收听收到的通知,自己没必要明确启动它。首先定义服务清单中有以下权限 -

android.permission.BIND_NOTIFICATION_LISTENER_SERVICE

<service android:name=".MyNotificationListener" 
     android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> 
    <intent-filter> 
     <action android:name="android.service.notification.NotificationListenerService" /> 
    </intent-filter> 
</service> 

另一个要照顾的是,你必须通过使用下面的意图授予的权限 -

Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"); 

或通过手动授予通知访问权限。

+0

要通过哪种方法传递此意图? – user3348949

+0

你能告诉我任何有效的例子吗? – user3348949

+0

上面提到的意图是用来打开通知设置。它会列出所有要求通知访问的应用程序。在使用通知侦听器服务之前,您必须授予对您的应用的通知访问权限 – Gautam

相关问题