Monday, 6 February 2023

 import android.app.Notification;

import android.app.NotificationChannel;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.os.Build;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {


   private ListView listView;

   private ArrayList<Notification> notificationsList;

   private NotificationAdapter adapter;

   private Button clearButton;


   @Override

   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);


      listView = findViewById(R.id.notification_list);

      clearButton = findViewById(R.id.clear_button);


      notificationsList = new ArrayList<>();

      adapter = new NotificationAdapter(this, notificationsList);

      listView.setAdapter(adapter);


      clearButton.setOnClickListener(new View.OnClickListener() {

         @Override

         public void onClick(View view) {

            notificationsList.clear();

            adapter.notifyDataSetChanged();

         }

      });

   }


   public void storeNotification(Notification notification) {

      notificationsList.add(notification);

      adapter.notifyDataSetChanged();

   }


   public static class NotificationListenerService extends android.service.notification.NotificationListenerService {


      private MainActivity mainActivity;


      @Override

      public void onCreate() {

         super.onCreate();

         mainActivity = (MainActivity) getApplicationContext();

      }


      @Override

      public void onNotificationPosted(StatusBarNotification sbn) {

         Notification notification = sbn.getNotification();

         Log.d("Notification", "Received notification: " + notification.toString());

         mainActivity.storeNotification(notification);

      }


      @Override

      public void onNotificationRemoved(StatusBarNotification sbn) {

         // Handle removal of notifications if needed

      }

   }

}




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">

   <ListView
      android:id="@+id/notification_list"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_weight="1"/>

   <Button
      android:id="@+id/clear_button"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="Clear Notifications"/>

</LinearLayout>

No comments:

Post a Comment