Open activity from a push notification

3

I am working on a Hello World application that receives PUSH notifications.

Everything works correctly, and where I install it, I receive notifications when I run the python script.

The problem that when the notification appears I do not know how to make you open the app.

The structure of the project is as follows:

  • MainActivity.java
  • NotificationsListenerService.java
  • RegistrationService.java
  • TokenRefreshListenerService.java

and a python send.py script

MainActivity.java:

package com.example.sergi.pruebapush;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, RegistrationService.class);
        startService(i);
    }
}

NotificationsListenerService.java

import com.google.android.gms.gcm.GcmListenerService;

public class NotificationsListenerService extends GcmListenerService {
}

RegistrationService.java

package com.example.sergi.pruebapush;

import android.app.IntentService; import android.content.Intent; import android.util.Log;

import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID;

import java.io.IOException;


public class RegistrationService extends IntentService {
    public RegistrationService() {
        super("RegistrationService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        InstanceID myID = InstanceID.getInstance(this);
        String registrationToken="";
        try {
            registrationToken = myID.getToken(
                getString(R.string.gcm_defaultSenderId),
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE,
                        null
                            );
            Log.d("Registration Token", registrationToken);
            GcmPubSub subscription = GcmPubSub.getInstance(this);
            subscription.subscribe(registrationToken, "/topics/my_little_topic", null);
        } catch (IOException e) {
            e.printStackTrace();
        }

    } }

Finally the script that I run every time I want a notification sent:

send.py

from urllib2 import *
import urllib
import json
import sys
MY_API_KEY="************************************************"
messageTitle = sys.argv[1]
messageBody = sys.argv[2]
data={
    "to" : "/topics/my_little_topic",
    "notification" : {
        "body" : messageBody,
        "title" : messageTitle,
        "icon" : "ic_launcher"
    }
}
dataAsJSON = json.dumps(data)
request = Request(
"https://gcm-http.googleapis.com/gcm/send",
dataAsJSON,
{ "Authorization" : "key="+MY_API_KEY,
"Content-type" : "application/json"
}
)
print urlopen(request).read()

Where can I control the notification to open the app?

    
asked by Sergio Cv 11.06.2016 в 13:05
source

2 answers

1

Within your onHandleIntent () method your RegistrationService class you can create the notification:

@Override
protected void onHandleIntent(Intent intent){
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);        
    String messageType = gcm.getMessageType(intent);
    Bundle extras = intent.getExtras();
    if (!extras.isEmpty()){  

    creaNotificacion();

    }        
    GCMBroadcastReceiver.completeWakefulIntent(intent);
}

Inside you can call the method to create the notification to which you define a PendingIntent , to open the Activity, the Main Activity is usually opened (open the application) or some fragment within it:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(ctx.getResources().getString(R.string.app_name))
                .setContentText("mi mensaje")
                .setWhen(System.currentTimeMillis());
    Intent notificacionIntent =  new Intent(ctx.getApplicationContext(), MainActivity.class);

                //Puedes definir valores extras para agregar en el Bundle del Intent.
                /*extras.putInt("seccion", 1);
                extras.putString("mensaje", "Este es mi mensaje");
                extras.putBoolean("esWidget", true);
                notIntent.putExtras(extras);*/
                PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1, notificacionIntent, FLAG_NONE);
                mBuilder.setContentIntent(pendingIntent);
                mBuilder.setAutoCancel(true);

@Sergiocv onHandleIntent () Used for receive the data of the push notification by the Google server, the obtaining of the token and the registration must be done previously, for example when you start your application for the first time.

    
answered by 12.06.2016 в 05:24
0

You can use the following code, creating a pending intent and set in the notification using the setLatestEventInfo method.

Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, MyClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    
answered by 11.06.2016 в 15:11