2015-10-04 2 views
0

Я получил мой registartion идентификатор моего устройства, и когда я пытаюсь отправить уведомление толчка от моего сервера на мое приложение, я получаю сообщение: преуспевающийприема Android толчок уведомление

{ «multicast_id»: some_id, "успех": 1, "провал": 0, "canonical_ids": 0, "Результаты": [{ "mESSAGE_ID": "0: some_id"}]}

Но мое приложение не показать какое-либо предупреждение или предупреждение. Я пробовал более 6 различных руководств в Интернете и до сих пор не смог найти способ получить эти уведомления из своего приложения.

Как получить это уведомление и показать его в своем приложении как push-уведомление, даже если пользователь без приложения?

public class GcmIntentService extends IntentService { 
    public static final int NOTIFICATION_ID = 1; 
    private NotificationManager mNotificationManager; 
    public GcmIntentService() { 
     super("GcmIntentService"); 
    } 
    @Override 
    protected void onHandleIntent(Intent intent) { 
     mNotificationManager = (NotificationManager) 
       this.getSystemService(Context.NOTIFICATION_SERVICE); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
       new Intent(this, MainActivity.class), 0); 
     NotificationCompat.Builder mBuilder = 
       new NotificationCompat.Builder(this) 
         .setSmallIcon(R.drawable.ic_launcher) 
         .setContentTitle("New Message!"); 
     mBuilder.setContentIntent(contentIntent); 
     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
     GcmBroadcastReceiver.completeWakefulIntent(intent); 
    } 
} 

Broadcast Receiver

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     ComponentName comp = new ComponentName(context.getPackageName(), 
       GcmIntentService.class.getName()); 
     startWakefulService(context, (intent.setComponent(comp))); 
     setResultCode(Activity.RESULT_OK); 
    } 
} 
+0

Возможно, push отправляется в ваше приложение, но вы не правильно его обрабатываете. Если вы не разделяете код своего приложения, я не могу ничего сделать. У вас есть соответствующие разрешения, добавленные в ваш манифест? – jmm

+0

, пожалуйста, напишите код, который вы используете для своего IntentService – AndroidEnthusiast

+0

Да, о разрешении, я уверен, но я понятия не имею, как обрабатывать отправленное вами уведомление. Пытался использовать все, что я нашел в Интернете, ничего не получилось. – EliKo

ответ

1
public class MyGcmListenerService extends GcmListenerService { 

private static final String TAG = "MyGcmListenerService"; 

@Override 
public void onMessageReceived(String from, Bundle data) { 
    String message = data.getString("message"); 

    // showing an alert activity if there is an active activity 

    Intent pushReceivedIntent = new Intent("Push"); 
    pushReceivedIntent.putExtras(data); 

    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); 
    ComponentName componentInfo = taskInfo.get(0).topActivity; 
    if(componentInfo.getPackageName().equalsIgnoreCase(Constants.APP_PACKAGE)){ 
     getApplicationContext().sendBroadcast(pushReceivedIntent); 
    } 
    else{ 
     // showNotification(data); 
    } 
} 

и ...

private void showNotification(Bundle data) { 
    String message = data.getString("message"); 

    Intent intent = new Intent(this, HomeActivity.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, 
      PendingIntent.FLAG_ONE_SHOT); 
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("") 
      .setContentText(message) 
      .setAutoCancel(true) 
      .setSound(defaultSoundUri) 
      .setContentIntent(pendingIntent); 

    NotificationManager notificationManager = 
      (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
} 

Это Намерение Сервис я использую,

public class RegistrationIntentService extends IntentService { 

private static final String TAG = "RegIntentService"; 
private static final String gcm_defaultSenderId = "1234556"; 

public RegistrationIntentService() { 
    super(TAG); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 

    try { 
     // [START register_for_gcm] 
     // Initially this call goes out to the network to retrieve the token, subsequent calls 
     // are local. 
     // [START get_token] 
     InstanceID instanceID = InstanceID.getInstance(this); 
     String token = instanceID.getToken(gcm_defaultSenderId, 
       GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); 
     // [END get_token] 


     // TODO: Implement this method to send any registration to your app's servers. 
     sendRegistrationToServer(token); 

     sharedPreferences.edit().putBoolean("SENT_TOKEN_TO_SERVER", true).apply(); 
     // [END register_for_gcm] 
    } catch (Exception e) { 
     Log.d(TAG, "Failed to complete token refresh", e); 
     // If an exception happens while fetching the new token or updating our registration data 
     // on a third-party server, this ensures that we'll attempt the update at a later time. 
     sharedPreferences.edit().putBoolean("SENT_TOKEN_TO_SERVER", false).apply(); 
    } 
    // Notify UI that registration has completed, so the progress indicator can be hidden. 
    Intent registrationComplete = new Intent("REGISTRATION_COMPLETE"); 
    LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); 
} 

private void sendRegistrationToServer(String token) { 
    Log.d("token ", token); 
    //TODO: Send This to server 
} 

}

Теперь, в ваших действиях onResume Method, вам необходимо добавить приемник.

protected void onResume() { 
    super.onResume(); 

    // receiver to get the Notification ALert 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction("PUSH"); 

    mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Intent intent1 = new Intent(this, SomeActivity.class); 
      intent1.putExtras(intent.getExtras()); 
      startActivity(intent1); 
     } 
    }; 
    registerReceiver(mReceiver, filter); 

    // Push Notification receiver 
    LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver, 
      new IntentFilter("REGISTRATION_COMPLETE")); 
} 

Также проверьте токены устройства.

+0

'Constants.ACTION_PUSH' Что это? У меня ошибка с этим классом Constants, у меня его нет. – EliKo

+0

@ user4177344: Извините, мой плохой. Это была константа, используемая для определения намерения. Редактировал мой ответ. Спасибо за это. –

+0

Хорошо, но что я с этим делаю? Просто добавьте этот код в качестве нового класса Java или что? Как реализовать его, чтобы показать мне push, который я отправил из своего php-кода? Я до сих пор не получаю никаких уведомлений – EliKo

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