EliKo
EliKo

Reputation: 101

receiving android push notification

I've got my registartion ID of my device, and when I'm trying to send push notification from my server to my app, I get successfull message:

{"multicast_id":SOME_ID,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:SOME_ID"}]}

But my app does not show any notifcation or alert. I've been trying more than 6 different guides on the web and still couldn't find a way to recieve this notifications from my app.

How to recieve this notification and show them in my app as push notification even when the user without the application on?

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

Upvotes: 0

Views: 236

Answers (1)

KP_G
KP_G

Reputation: 470

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

and...

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

This is the Intent Service I use,

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
}

}

Now, In your activities onResume Method, u need to add the receiver.

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

Also, check the device tokens as well.

Upvotes: 1

Related Questions