1

"Accept"및 "Reject"라는 두 개의 작업 버튼이있는 사용자에게 Notification을 전달합니다.알림의 작업 버튼에 onClickListener 설정

사용자가 "수락"을 클릭하자마자 몇 가지 조건을 확인한 다음 그에 따라 진행하고 싶습니다. 사용자가 의도로 지정된 화면으로 이동하기를 원하지 않습니다.

업데이트 : 코드를 구현할 때 알림이 도착하지만 '수락'또는 '거부'버튼을 클릭해도 아무 일도 일어나지 않습니다.

여기에 내가 뭘 내용은 다음과 같습니다

 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> 

은 알려 주시기 바랍니다.

+0

'MyBroadcastReceiver'를 매니페스트에 추가 했습니까? –

+0

@DavidWasser 예 ... 수정 된 질문보기 –

+0

'MyBroadcastReceiver'는 '서비스'의 내부 클래스입니까? 아니면 파일 자체에 있습니까? 그것은 내부 클래스가되어서는 안됩니다. 또한, 당신은'MyBroadcastReceiver'의 인스턴스를 생성하고 ACTION에 IntentFilter를 등록하지만, 당신은'Intent'에서 결코 ACTION을 사용하지 않습니다. –

답변

2

이렇게하려면 BroadcastReceiver을 사용할 수 있습니다. 사용자가 '수락'버튼을 탭하면 onReceive()의 조치를 처리합니다 (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); 

나는이를 더 잘 이해하고 구현하기 위해 this repository at github을 만들었습니다.

+0

그러나'BroadcastReceiver'에서 다른 활동에있는 변수에 접근하여 조건을 확인하려면 어떻게해야합니까? –

+0

활동에 [이 답변을 따르십시오] (http://stackoverflow.com/a/41090828/3682535) 내부 BroadcastReceiver를 작성하십시오. – rupinderjeet

+0

안녕하세요. 귀하의 답변을 따른 후에 위의 질문에 새 코드를 작성하고 업데이트했습니다. 모양을 확인하고 현재 발생하는 문제를 확인하십시오. –