1

I'm delivering a Notification to the user which has two action buttons "Accept" and "Reject".

As soon as a user clicks "Accept", I want to check few conditions and then proceed accordingly. I don't want the user to just navigate to the screen which is specified in the intent.

UPDATE: on implementing below code, the notifcation is arriving but on clicking the "Accept" or "Reject" button, nothing is happening!

Here's what I'm doing:

        public class MyService extends Service {

        DatabaseReference firebaseDatabaseFollowers;
        boolean newRequestBool;
        NotificationCompat.Builder mBuilder;
        String pBy, ss;
        GeoFire geoFire;
        GeoQuery geoQuery;
        Query query;

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();

            firebaseDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://***-***.firebaseio.com/");
            geoFire = new GeoFire(FirebaseDatabase.getInstance().getReferenceFromUrl("https://***-***.firebaseio.com/geofire"));
            query = firebaseDatabaseFollowers.child("users").child(MainActivity.uid).child("child");

            final SharedPreferences sharedPref2 = PreferenceManager.getDefaultSharedPreferences(this);
            newRequestBool = sharedPref2.getBoolean(SettingsActivity.KEY_PREF_NOTIF_NEW_REQUEST, true);

            ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
            if (ActivityCompat.checkSelfPermission(getBaseContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getBaseContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationProvider.getLastKnownLocation()
                    .subscribe(new Action1<Location>() {
                        @Override
                        public void call(Location location) {
                            currentLatDouble = location.getLatitude();
                            currentLngDouble = location.getLongitude();
                            geoQuery = geoFire.queryAtLocation(new GeoLocation(currentLatDouble, currentLngDouble), Double.parseDouble(MainActivity.radiusValue));

                            firebaseDatabaseFollowers.child("child").addChildEventListener(new ChildEventListener() {
                                @Override
                                public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                                    if (dataSnapshot.getValue() != null) {

                                        id = dataSnapshot.getKey();

                                        geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
                                            @Override
                                            public void onKeyEntered(String key, GeoLocation location) {
                                                firebaseDatabase.child("child").child(key).addListenerForSingleValueEvent(new ValueEventListener() {
                                                    @Override
                                                    public void onDataChange(DataSnapshot dataSnapshot) {
                                                        if (dataSnapshot != null) {
                                                            Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
                                                            pBy = newRequest.get("pBy");
                                                            ss = newRequest.get("ss");

                                                            if (String.valueOf(newRequestBool).equals("true")) {
                                                                final int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);

                                                                Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
                                                                notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationNewRService());
                                                                PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                                                                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                                                                alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);

                                                            }

                                                        } else {
                                                            Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
                                                        }
                                                    }

                                                    ...
                                        });

                                    } else {
                                        Toast.makeText(getBaseContext(), "no data", Toast.LENGTH_SHORT).show();
                                    }
                                }

                                ...
                            });

                        }
                    });

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            Toast.makeText(getBaseContext(), "Service stopped", Toast.LENGTH_SHORT).show();
        }

        private Notification getNotificationNewRequestService() {

    //        String id = firebaseDatabaseFollowers.child("game-requests").push().getKey();

            mBuilder =
                    new NotificationCompat.Builder(getBaseContext())
                            .setSmallIcon(R.mipmap.app_icon_1)
                            .setContentTitle("Title")
                            .setContentText("text...");

            Intent resultIntent = new Intent(getBaseContext(), Profile.class);

            // Because clicking the notification opens a new ("special") activity, there's
            // no need to create an artificial back stack.
            PendingIntent resultPendingIntent =
                    PendingIntent.getActivity(
                            getBaseContext(),
                            0,
                            resultIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT
                    );

// register receiver in constructor/onCreate()
        MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(getString(R.string.broadcast_id));
        registerReceiver(myBroadcastReceiver, myIntentFilter);

            // for action button
            Intent actionIntent = new Intent(this, MyBroadcastReceiver.class);
            PendingIntent actionPendingIntent = PendingIntent
                    .getBroadcast(getBaseContext(),
                            0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

sendBroadcast(actionIntent);

            mBuilder.setAutoCancel(true);
    //        mBuilder.setContentIntent(resultPendingIntent);
            mBuilder.addAction(R.drawable.ic_accepted_request_black_24dp, "Accept", actionPendingIntent);
            mBuilder.addAction(R.drawable.ic_close_light, "Reject", null);

            return mBuilder.build();
        }

        public class MyBroadcastReceiver extends BroadcastReceiver {

public MyBroadcastReceiver(){
            super();
        }

            @Override
            public void onReceive(Context context, Intent intent) {

Log.d("BROADCAST", "Broadcast received");
            if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id))) {

                Intent intent1 = new Intent(MyService.this, MainActivity.class);
                startActivity(intent1);

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (String.valueOf(difference).contains("-")) {
                             // do the logic
                        } else if (String.valueOf(difference).equals("0")){
                            // do the logic
                        } else if (!String.valueOf(differenceCurrentStartTime).contains("-")) {
                            // do the logic
                        } else if (!String.valueOf(difference).equals("0") && !String.valueOf(difference).contains("-") && String.valueOf(differenceCurrentStartTime).contains("-")) {
                            // do the logic

                        }
                    }
                }, 1000);

            }
}
        }

    }

Here's AndroidManifest.xml:

<receiver android:name=".MyBroadcastReceiver">
        <intent-filter>
            <action android:name="com.abc.ccc.BROADCAST_EVENT">
            </action>
        </intent-filter>

    </receiver>

Here's strings.xml:

// define a Broadcast Intent Action in String resources
    <string name="broadcast_id">com.abc.ccc.BROADCAST_EVENT</string>

Please let me know.

Hammad Nasir
  • 2,681
  • 6
  • 44
  • 120
  • Have you added `MyBroadcastReceiver` to the manifest? – David Wasser Dec 12 '16 at 13:28
  • @DavidWasser yes... see the edited question please – Hammad Nasir Dec 12 '16 at 13:34
  • Is `MyBroadcastReceiver` an inner class of your `Sevice`? Or is it in a file all by itself? It should NOT be an inner class. Also, you are creating an instance of `MyBroadcastReceiver` and registering an `IntentFilter` for the ACTION, but you never use the ACTION in the `Intent` – David Wasser Dec 12 '16 at 13:45
  • @DavidWasser yeah.. it is an inner class. I followed this answer: http://stackoverflow.com/a/41090828/6144372 I know I have messed this up. Can you please write a clear code for me as an answer? What should I be doing? – Hammad Nasir Dec 12 '16 at 14:46

1 Answers1

2

You can use a BroadcastReceiver to do this. When a user taps "Accept" button, handle its action in onReceive() of your BroadcastReceiver.

// for notification itself
Intent notificationIntent = (new Intent()).setAction(INTENT_ACTION_HERE);
PendingIntent notificationPendingIntent = PendingIntent
        .getBroadcast(context, NOTIFICATION_INTENT_REQUEST_ID, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

// for action button
Intent actionIntent = new Intent(this, YourBroadcastReceiver.class);
PendingIntent actionPendingIntent = PendingIntent
        .getBroadcast(context,  ACTION_INTENT_REQUEST_ID, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

// execute onNotificationClick
mNotificationBuilder.setContentIntent(notificationPendingIntent);

// execute onButtonClick
mNotificationBuilder.addAction(R.drawable.button_icon, BUTTON_TEXT, actionPendingIntent);

I have made this repository at github to understand and implement this better.

rupinderjeet
  • 2,597
  • 24
  • 44
  • But how do I access the variables which are in another activity in the `BroadcastReceiver` for checking the conditions? – Hammad Nasir Dec 12 '16 at 03:49
  • Write an inner BroadcastReceiver in the activity, [follow this answer](http://stackoverflow.com/a/41090828/3682535). – rupinderjeet Dec 12 '16 at 06:47
  • hey. after following your answer, I have written the new code and updated it in the question above. Please have a look and also see the problem occurring now. – Hammad Nasir Dec 12 '16 at 11:31
  • You forgot to register and unregister the receiver. Follow that answer to register/unregister it. – rupinderjeet Dec 12 '16 at 11:43
  • what is a broadcast id? Why and when is it used? – Hammad Nasir Dec 12 '16 at 11:51
  • It is just an id for broadcasts. You send a broadcast when user taps Accept button. Then, MyBroadcastReceiver uses this id to identify correct Broadcast from all broadcasts. So, for e.g. if you send a broadcast with 'MyFirstBroadcast', then MyBroadcastReceiver will only listen to this Broadcast. And, when this broadcast is received, it executes your code. – rupinderjeet Dec 12 '16 at 12:00
  • please help, bro. Nothing is happening after clicking either buttons. I have updated the code in question. Please take a look. – Hammad Nasir Dec 12 '16 at 17:40
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/130429/discussion-between-rupinderjeet-and-hammad-nasir). – rupinderjeet Dec 12 '16 at 17:43
  • the github repo did the job for me. Thanks @rupinderjeet! Can you please help with this too: http://stackoverflow.com/questions/41125004/notification-not-getting-removed-on-clicking-action-button-even-after-providing – Hammad Nasir Dec 14 '16 at 06:22