当收到来自特定应用程序的通知时,即使应用程序未运行,也要运行我的特定代码块

时间:2019-10-01 10:01:57

标签: android notifications broadcastreceiver

是否有任何广播接收器或NotificationListnerService类。 基本上,我想在收到特定应用的通知时在后台运行代码,并在UI线程上显示一些结果。您可以将其与类似WhatsApp或Messenger收到消息时Chathead会自动激活的事情联系起来 我是android的新手,对不起,问错什么 如果您知道答案,请分享一些工作代码。

1 个答案:

答案 0 :(得分:0)

您需要创建服务,如下所示

Manifest.xml

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

添加权限

android.permission.BIND_NOTIFICATION_LISTENER_SERVICE

和服务

public class MyNotificationListenerextends 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");  

}  }