1

Я пытаюсь реализовать глубокую привязку через уведомление Localitics Push в Android. В приведенном ниже коде я могу получить пару значений ключа, которую я отправляю через панель управления Localitics при создании уведомления Push. Однако мое требование состоит в том, чтобы открыть конкретное действие на основе пары ключ/значение, которую я получаю в Push Notification.Внедрение глубоких ссылок в Localtics Push Notification

 public class GCMReceiver extends BroadcastReceiver { 
    String deeplink_key = "KEY_DEEPLINK"; 
    public static final String CUSTOM_INTENT ="com.mypackage.action.TEST"; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
    Bundle extras = intent.getExtras(); 
    String deeplinkValues = extras.getString(deeplink_key); 
    Log.i("BASE", "deeplinkValues: " + deeplinkValues); 
    String action = intent.getAction(); 
    Uri data = intent.getData(); 

    Intent gotoOffersIntent = new Intent(context,OffersDisplayActivity.class); 
    gotoOffersIntent.putExtra(deeplink_key, deeplinkValues); 
// gotoOffersIntent.setAction(CUSTOM_INTENT); 
    /*The below line opens the OffersDisplayActvity directly when Push notification is received*/ 
    context.startActivity(gotoOffersIntent); 


// context.sendOrderedBroadcast(gotoOffersIntent, null); 

    PushReceiver pushReceiver = new PushReceiver(); 
    pushReceiver.onReceive(context, intent); 

    GCMBroadcastReceiver gcmBroadcastReceiver = new GCMBroadcastReceiver(); 
    gcmBroadcastReceiver.onReceive(context, intent); 

} 
} 

С выше кода я в состоянии открыть OffersDisplayActivity на PushNotification получил, но я хочу OffersDisplayActivity быть открыт, когда я нажимаю на уведомления Push.

Пожалуйста, помогите мне с этим. Благодарю вас!

ответ

3

Вам не нужна глубокая привязка для вашего требования. Местные ребята иногда дезинформируют разработчиков, заявляя, что вам нужна дезадаптация для пользовательских типов уведомлений.

Мы сделали то же самое, что вы хотите сделать в своем приложении с локализацией. 1) Получите информацию о локализации в уже реализованном GCMBroadcastReciever. 2) В вас сообщении держать одно поле для определения того, какие активности вы хотите открыть

Если вы добавили какой-либо дополнительный класс для приема намерения с следующими действиями

com.google.android.c2dm.intent.RECEIVE 

кроме вашего GCMReceiver затем удалить его ..

Таким образом, все уведомления поступали либо с вашего сервера, либо из локализации, который будет получен в методе onReceive.

Вот полный пример того, что мы сделали для Localytics и наш собственный сервер ..

Android Manifest.xml

<service 
      android:name=".gcm.CustomInstanceIDListenerService" 
      android:exported="false"> 
      <intent-filter> 
       <action android:name="com.google.android.gms.iid.InstanceID" /> 
      </intent-filter> 
     </service> 

     <receiver 
      android:name="com.google.android.gms.gcm.GcmReceiver" 
      android:permission="com.google.android.c2dm.permission.SEND"> 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
       <!-- for Gingerbread GSF backward compat --> 
       <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> 
       <category android:name="com.nearfox.android" /> 
      </intent-filter> 
     </receiver> 

     <service android:name=".gcm.CustomGCMListenerService"> 
      <intent-filter> 
       <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
      </intent-filter> 
     </service> 
     <service 
      android:name=".gcm.RegistrationIntentService" 
      android:exported="false" /> 

в CustomGCMListenerService.java

public class CustomGCMListenerService extends GcmListenerService { 

    private static final String TAG = "CustomGCMListener"; 

    public interface MESSAGE_TYPE { 
     String NOTIFICATION_NEWS = "news_notification"; 
     String NOTIFICATION_EVENT = "event_notification"; 
    } 

    @Override 
    public void onMessageReceived(String from, Bundle data) { 
     if (data.containsKey("msg_type") && data.getString("msg_type") != null) { 
      String messageType = data.getString("msg_type"); 
      if (messageType.equals(MESSAGE_TYPE.NOTIFICATION_NEWS)) { 
       String newsJson = data.getString("news_body"); 
       try { 
        JSONObject jsonObject = new JSONObject(newsJson).getJSONObject("message"); 
        generateNotification(this, jsonObject.getString("title"), "", MESSAGE_TYPE.NOTIFICATION_NEWS, data); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
        Log.i(TAG, "Notification Parsing Error"); 
        return; 
       } 
      } else if (messageType.equals(MESSAGE_TYPE.NOTIFICATION_EVENT)) { 
       String newsJson = data.getString("body"); 
       try { 
        JSONObject jsonObject = new JSONObject(newsJson).getJSONObject("message"); 
        generateNotification(this, jsonObject.getString("title"), "", MESSAGE_TYPE.NOTIFICATION_EVENT, data); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
        Log.i(TAG, "Notification Parsing Error"); 
        return; 
       } 
      } 
     } 
    } 


    public static void generateNotification(Context context, String message, String ids, String messageType, Bundle data) { 
     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); 
     notificationBuilder.setSmallIcon(R.drawable.small_notification_icon); 
     notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_icon)); 
     String title = context.getString(R.string.app_name); 
     notificationBuilder.setContentTitle(title); 
     notificationBuilder.setContentText(message); 
     Notification notification ; 


     if (messageType.equals(MESSAGE_TYPE.NOTIFICATION_NEWS)) { 
      Intent notificationIntent = new Intent(context, SingleNewsActivity.class); 
      notificationIntent.putExtra("source", "notification"); 
      notificationIntent.putExtra("news_title", message); 
      PendingIntent intent = 
        PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
      notificationBuilder.setContentIntent(intent); 
     } else if (messageType.equals(MESSAGE_TYPE.NOTIFICATION_EVENT)) { 
      Intent notificationIntent = new Intent(context, SingleEventActivity.class); 
      notificationIntent.putExtra("source", "notification"); 
      notificationIntent.putExtra("event_title", data); 
      PendingIntent intent = 
        PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
      notificationBuilder.setContentIntent(intent); 
     } 
     notificationBuilder.setContentText(message); 
     notificationBuilder.setStyle(new android.support.v4.app.NotificationCompat.BigTextStyle().bigText(message)); 
     notification = notificationBuilder.build(); 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 
     notification.defaults |= Notification.DEFAULT_SOUND; 
     notification.defaults |= Notification.DEFAULT_VIBRATE; 
     notificationManager.notify(0, notification); 

    } 
} 

Так здесь вы можете увидеть если из локалистики или с вашего собственного сервера вы отправляете сообщение GCM, которое содержит поле "message_type"="news_notification", тогда пользователь нажимает на уведомление, откроется SingleNEwsActivity и если "message_type"=event_notification", то он откроется SingleEventActivity .. также здесь вы можете слить дополнительные данные с notificationIntent.putExtra()

+0

Большое спасибо ..! Пользовательская реализация работала .. :) – Vina

+0

добро пожаловать. –

2

Сравните свою пару «ключ-значение» и на ее основе вызовите активность желания от намерения при генерации push-уведомления. Он будет называть его, когда пользователь нажимает на уведомление.

// Set the action to take when a user taps the notification 
    Intent resultIntent = new Intent(context, LoginActivity.class); 
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    if (notificationObj!=null) { 
     resultIntent.putExtra(UserDefault.pushJSONObj, notificationObj); 
    } 

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
    mBuilder.setContentIntent(resultPendingIntent); 

Здесь notificationObj - это любой параметр, который вы хотите передать своей деятельности.

+0

Спасибо, Bini. Вышеупомянутое решение работает для обычного уведомления Push, где мы создаем собственный конструктор уведомлений. Но здесь, поскольку я использую уведомление Localitics Push, я не могу получить здесь объект «mBuilder», чтобы установить PendingIntent. Вот где я застрял .. – Vina

 Смежные вопросы

  • Нет связанных вопросов^_^