在通知

时间:2016-12-11 19:37:04

标签: android onclicklistener android-notifications android-pendingintent

我向用户发送Notification,其中有两个操作按钮"接受"和"拒绝"。

一旦用户点击"接受",我想检查几个条件,然后相应地继续。我不希望用户只是导航到意图中指定的屏幕。

更新:关于实施以下代码,通知已到达,但点击了"接受"或"拒绝"按钮,什么都没发生!

这就是我正在做的事情:

        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);

            }
}
        }

    }

此处AndroidManifest.xml

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

    </receiver>

此处strings.xml

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

请告诉我。

1 个答案:

答案 0 :(得分:2)

您可以使用BroadcastReceiver执行此操作。当用户点击&#34;接受&#34;按钮,在onReceive()的{​​{1}}处理其操作。

BroadcastReceiver

我已让this repository at github更好地理解并实施此功能。

相关问题