Android Push Notification with Image using GCM, php & mysql Example Part 2

Please follow and like us:

Android Push Notification with Image

Android Push Notification with Image Example part 2 contains the Android side logic for getting Android Push Notification with Image in your Android App. If you miss the part 1 of server side setup for push notification then advice to see it first.  Let’s understand the Android side logic for sending Push Notification with Image step by step…


Android Push Notification with Image

Android Push Notification with Image Implementation

We need to add following things to mainifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nkdroid.pushnotification">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <!-- GCM permissions -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.nkdroid.pushnotification.permission.C2D_MESSAGE" android:protectionLevel="signature" />

    <uses-permission android:name="com.nkdroid.pushnotification.permission.C2D_MESSAGE" />

    <application android:name=".app.MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".GCM.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="com.nkdroid.pushnotification" />
            </intent-filter>
        </receiver>

        <service android:name=".GCM.GcmMessageHandler" />

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

    </application>

</manifest>

Add following dependency to your app’s build gradle file.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.nkdroid.pushnotification"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.google.code.gson:gson:2.4'
    compile 'com.pnikosis:materialish-progress:1.5'
    compile 'com.mcxiaoke.volley:library:1.0.6'
}

Add following java files for GCM push notification logic in GCM folder.

package com.nkdroid.pushnotification.GCM;

/**
 * Created by nirav on 28-10-2014.
 */

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // Explicitly specify that GcmMessageHandler will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmMessageHandler.class.getName());

        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}
package com.nkdroid.pushnotification.GCM;

/**
 * Created by nirav on 28-10-2014.
 */

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.nkdroid.pushnotification.MainActivity;
import com.nkdroid.pushnotification.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class GcmMessageHandler extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context context;
    Bitmap icon;
    PendingIntent contentIntent;

    public GcmMessageHandler() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        this.context = this;
        final Bundle extras = intent.getExtras();
        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle

            sendNotification(extras, this);

        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(final Bundle response, final Context context) {
        new generatePictureStyleNotification(this, response.getString("title"), response.getString("message"), response.getString("image_url")).execute();
    }


    public class generatePictureStyleNotification extends AsyncTask<String, Void, Bitmap> {

        private Context mContext;
        private String title, message, imageUrl;

        public generatePictureStyleNotification(Context context, String title, String message, String imageUrl) {
            super();
            this.mContext = context;
            this.title = title;
            this.message = message;
            this.imageUrl = imageUrl;

        }

        @Override
        protected Bitmap doInBackground(String... params) {

            InputStream in;
            try {
                URL url = new URL(this.imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                in = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(in);
                return myBitmap;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);

            icon = BitmapFactory.decodeResource(getResources(),
                    R.mipmap.ic_launcher);

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

            contentIntent = PendingIntent.getActivity(mContext, 0,
                    new Intent(mContext, MainActivity.class).putExtra("is_from_notification", true), 0);
            builder = new NotificationCompat.Builder(context)
                    .setAutoCancel(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setLargeIcon(icon)
                    .setContentTitle(title)
                    .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(result))
                    .setContentText(message
                    );

            builder.setContentIntent(contentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        }
    }
}

We need Volly library for calling API for registering registration id to server. Add following java files in util folder.

package com.nkdroid.pushnotification.util;


import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.nkdroid.pushnotification.app.MyApplication;

import org.json.JSONArray;
import org.json.JSONObject;

public abstract class GetServiceCall implements IService {

    public abstract void response(String response);

    public abstract void error(VolleyError error);

    private String url;
    String response = null;

    public static int TYPE_JSONOBJECT = 0;
    public static int TYPE_JSONARRAY = 1;
    public static int TYPE_STRING = 2;
    public int type = 0;

    public GetServiceCall(String url, int type) {
        super();
        this.url = url;
        this.type = type;
    }

    // Main implementation of calling the webservice.

    public synchronized final GetServiceCall start() {

        call();

        return this;

    }

    public void call() {

        switch (type) {

            // case  for requesting json object
            case 0:

                JsonObjectRequest request = new JsonObjectRequest(url, null,
                        new Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject jobj) {

                                response(jobj.toString());

                            }
                        }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError e) {

                        error(e);
                    }
                });

                MyApplication.getInstance().addToRequestQueue(request);

                break;


            // case for requesting json array
            case 1:

                JsonArrayRequest request2 = new JsonArrayRequest(url,
                        new Listener<JSONArray>() {

                            @Override
                            public void onResponse(JSONArray jArray) {

                                response(jArray.toString());
                            }
                        }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {

                        error(arg0);
                    }
                });

                MyApplication.getInstance().addToRequestQueue(request2);

                break;

            case 2:

                break;

        }

    }

}
package com.nkdroid.pushnotification.util;

import com.android.volley.VolleyError;

public interface IService {
	
	public void response(String response);
	public void error(VolleyError error);

}
package com.nkdroid.pushnotification.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;


public class PrefUtils {

    public static void setNotificationId(String login, Context ctx) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("notification", login);
        editor.apply();
    }

    public static String getNotificationId(Context ctx) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
        return preferences.getString("notification", "");

    }

}

We need to create POJO class for getting JSON API response. Add following java file in model folder.

package com.nkdroid.pushnotification.model;

import com.google.gson.annotations.SerializedName;

/**
 * Created by nirav on 01/05/16.
 */
public class JSONresponse {

    @SerializedName("status")
    private int status;
    @SerializedName("msg")
    private String message;

    public String getMessage() {
        return message;
    }

    public int getStatus() {
        return status;
    }

}

We need to initialize volly logic in application level class. Add following java file in app folder.

package com.nkdroid.pushnotification.app;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * Application class that called once when application is installed for the first time on device.
 * This class includes the integration of Volly [third party framework for calling webservices]
 */
public class MyApplication extends Application {


    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static MyApplication sInstance;

    /**
     * A class that helps to store database file from assets to
     */


    @Override
    public void onCreate() {

        super.onCreate();

        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "com.charityapp.osman",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

        // initialize the singleton
        sInstance = this;

    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized MyApplication getInstance() {
        return sInstance;
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified
     * then it is used else Default TAG is used.
     *
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        VolleyLog.d("Adding request to queue: %s", req.getUrl());
        getRequestQueue().add(req);
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     *
     * @param req
     * @param
     */
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

    public void cancelAll() {
        try {
            mRequestQueue.cancelAll(null);
        } catch (Exception e) {

        }
    }
}

Add following code for your main activity layout file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.nkdroid.pushnotification.MainActivity">

    <TextView android:textSize="18sp" android:textStyle="bold" android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Android Push Notification with Image Example" />

    <ImageView android:layout_centerInParent="true" android:background="@drawable/nkdroid" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>

MainActivity file contains the logic of generating registration id, submit it on server and get push notification.

package com.nkdroid.pushnotification;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.GsonBuilder;
import com.nkdroid.pushnotification.model.JSONresponse;
import com.nkdroid.pushnotification.util.GetServiceCall;
import com.nkdroid.pushnotification.util.PrefUtils;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {


    private GoogleCloudMessaging gcm;
    private String regid;
    private String PROJECT_NUMBER = "ADD_YOUR_PROJECT_NUMER_HERE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (PrefUtils.getNotificationId(MainActivity.this).length() == 0) {
            getRegId();
        }

    }

    public void getRegId() {


        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
                    }
                    regid = gcm.register(PROJECT_NUMBER);
                    Log.e("GCM ID :", regid);
                    if (regid == null || regid == "") {
                        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                        alert.setTitle(getString(R.string.ERROR));
                        alert.setMessage(getString(R.string.INTERNALSERVERERROR));
                        alert.setPositiveButton(getString(R.string.TRYAGIN), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                getRegId();
                                dialog.dismiss();
                            }
                        });
                        alert.setNegativeButton(getString(R.string.EXIT), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                MainActivity.this.finish();
                            }
                        });
                        alert.show();
                    } else {
                        Log.e("registration id:", regid);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                                progressDialog.setMessage("Registering Device...");
                                progressDialog.show();
                                new GetServiceCall("http://www.nkdroidsolutions.com/push_demo/add_registration_id.php?registration_id=" + regid, GetServiceCall.TYPE_JSONOBJECT) {

                                    @Override
                                    public void response(String response) {

                                        progressDialog.dismiss();
                                        JSONresponse jsoNresponse = new GsonBuilder().create().fromJson(response, JSONresponse.class);
                                        if (jsoNresponse.getStatus() == 1) {
                                            PrefUtils.setNotificationId(regid, MainActivity.this);
                                            Toast.makeText(MainActivity.this, jsoNresponse.getMessage(), Toast.LENGTH_LONG).show();
                                        } else if (jsoNresponse.getStatus() == 2) {
                                            PrefUtils.setNotificationId(regid, MainActivity.this);
                                            Toast.makeText(MainActivity.this, jsoNresponse.getMessage(), Toast.LENGTH_LONG).show();
                                        } else if (jsoNresponse.getStatus() == 0) {
                                            Toast.makeText(MainActivity.this, jsoNresponse.getMessage(), Toast.LENGTH_LONG).show();
                                        }

                                    }

                                    @Override
                                    public void error(VolleyError error) {
                                        progressDialog.dismiss();
                                        error.printStackTrace();
                                    }

                                }.call();
                            }
                        });


                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                    Log.e("error", ex.toString());
                }
                return null;
            }
        }.execute();
    } // end of getRegId

}

Android Push Notification with Image

Hope you like our simple tutorial about implementing Android Push Notification with Image using GCM and Server Side (PHP & MySQL). Stay connected for latest Android materials.

nirav kalola