Путаница по поводу нового API GoogleCloudMessaging (а не старого)

я следовал руководству по GCM, доступному на официальном сайте:

http://developer.android.com/google/gcm/gs.html

и я успешно реализовал его в своем приложении ... но, поскольку я новичок в Android, у меня мало путаницы в отношении GCM, и я был бы очень признателен, если бы кто-то мог прояснить эти моменты.

  • я написал PHP-скрипт (найденный в Google) и жестко закодировал свой идентификатор регистрации (только для тестирования), когда я запускаю скрипт, я получаю уведомление на своем устройстве ... но я не хочу получать уведомление, а хочу молча получать данные и обрабатывать его на моем устройстве. Является ли это возможным?? вот PHP-код:

    $regID=$_REQUEST['regID'];
    $registatoin_ids=array($regID);
    $msg=array("message"=>'HI Wasif');
    $url='https://android.googleapis.com/gcm/send';
    $fields=array
     (
      'registration_ids'=>$registatoin_ids,
      'data'=>$msg
     );
    $headers=array
     (
      'Authorization: key=MY-REG-KEY',
      'Content-Type: application/json'
     );
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
    $result=curl_exec($ch);
    curl_close($ch);
    echo $result;
    
  • Во-вторых, я хочу настроить уведомление, которое я получаю на своем устройстве. Я получаю такое уведомление... (см. рисунок ниже), но я хочу заменить текст заголовка «Уведомление GCM» на имя моего приложения, и сообщение должно отображаться правильно (не так, как ключ, текст значения), а также изменить изображение уведомления ... может ли кто-нибудь предоставить учебник, как это сделать в новом API GoogleCloudMessaging ?? (пожалуйста, не указывайте старые методы, если они не совпадают с новым API GoogleCouldMessaging) введите здесь описание изображения

    КОД ВЕЩАТЕЛЬНОГО ПРИЕМНИКА: открытый класс GcmBroadcastReceiver расширяет WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
    }
    

person Wasif Khalil    schedule 11.10.2013    source источник
comment
пожалуйста, покажите нам свой BroadCastReciever для gcm. Там должен быть Notificationbuilder.   -  person A.S.    schedule 11.10.2013
comment
пожалуйста, смотрите выше, я добавил код BroadCastReciever   -  person Wasif Khalil    schedule 11.10.2013
comment
@ТАК КАК. спасибо брат ты дал мне подсказку и я сделал это! Я настроил уведомление внутри GCMIntentService.java, большое спасибо!!   -  person Wasif Khalil    schedule 11.10.2013


Ответы (1)


Надеюсь, эта ссылка поможет: GCM

1) Если вы не хотите получать уведомление на устройстве, удалите код уведомления из класса GCMIntentService в методе generateNotification().

2) Вы можете указать имя своего приложения, значок приложения, реализовав следующий код в методе generateNotification():

private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);      

}

Надеюсь это поможет.

person Siddharth_Vyas    schedule 14.10.2013