Last updated on February 6th, 2017 at 11:17 am

Update follow this post to send push notification using firebase

 

In this post i am going to explain how to send image in your push notification. Image notification is very useful to promote your product or if you are building app for e-commerce to attract more customer to your online store. So here is simple code for push notification with image which help to build notification and service like that.

Send image push notification google GCM - trinitytuts

Demo

To test demo please download sample .apk file from above download link

Server side code for GCM:

Create new php file in your server directory where we save user id and also send push notification to user. Copy below code and paste in your file, here i create a .txt where i save user GCM ID and also send image after upload. Before we go further please make sure your server directory have read write permission because i am creating a txt file from where i read GCM id to send notification.

saveid.php

<?php
$req = $_POST['r'];
$get = json_decode(stripslashes($req));
if(file_put_contents("GCMRegId.txt", $get->reg))
	$msg['status'] = 1;
else
	$msg['status'] = 0;

	header('Access-Control-Allow-Origin: *');
	header('Access-Control-Allow-Headers: Content-Type');
	header('Content-Type: application/json');
	echo json_encode($msg);
ob_flush();
?>

Above code help you create .txt file and save text in that file.

index.php

<!DOCTYPE html>
<?php
	function sendPush($registatoin_ids, $message) {
		//Google cloud messaging GCM-API url
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
			'registration_ids' => array($registatoin_ids, "<your_server_key>"),
			'data' => array("msg" => $message),
		); 
		// Google Cloud Messaging GCM API Key
		define("GOOGLE_API_KEY", "AIzaSyDVL9ZVPZamdVnh6TVsTv4g_ze-jFEvJv4"); // GCM server key
        $headers = array(
		'Authorization: key=' . GOOGLE_API_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_VERIFYHOST, 0); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
		//print_r($result);
		if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
			//curl_close($ch);
		}
		
        return $result;
	}
	$msg = "";
	if(isset($_GET['push'])){
		if((isset($_POST['message'])) && (!empty($_POST['message'])) && (!empty($_FILES["fileToUpload"]['name']))){
			$target_dir = "uploads/";
			$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
			
			if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
				$message = array("msg"=> $_POST['message'], "image" =>"http://demo.trinitytuts.com/push/".$target_file);
				$gcmRegID = file_get_contents("GCMRegId.txt");
				sendPush($gcmRegID, $message);
				$msg = "Message sent";
			} else {
				$msg = "Sorry, there was an error uploading your file.";
			}		
		}
	}
?>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
		<title>Test push notification</title>
		
		<!-- Bootstrap -->
		<!-- Latest compiled and minified CSS -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
		
		<!-- Optional theme -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
		<!-- Latest compiled and minified JavaScript -->
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
		
		<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
		<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
		<!--[if lt IE 9]>
			<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
			<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
		<![endif]-->
	</head>
	<body>
		<div class="container"> 
			<br/>
			<div class="row">
				<div class="col-md-4">&nbsp;</div>
				<div class="col-md-4">
					<form action="?push=1" method="post" enctype="multipart/form-data">
						<div class="form-group">
							<label for="exampleInputEmail1">Enter message</label>
							<input type="text" name="message" class="form-control" id="exampleInputEmail1" placeholder="Message">
						</div>
					<div class="form-group">
					<label for="exampleInputFile">File input</label>
					<input type="file" id="exampleInputFile" name="fileToUpload">
					</div>
					<button type="submit" class="btn btn-default">Submit</button>
					</form>
					<?php if(!empty($msg)){?>
					<div class="alert alert-success"><?=$msg?></div>
					<?php }?>
				</div>
				<div class="col-md-4">&nbsp;</div>
			</div>
			
		</div> 
	</body>
</html>

Above code load registration id from your text file and also upload image and send it to your device. Note: please upload small size image so that image load easily. Also enter your server key above.

Android code

Step 1. Create new android project in android studio.

Step 2. Open project AndroidManifest.xml file and add some require permission, receiver and Google Api key in it.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.trinityimagegcm">

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

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

    <uses-permission android:name="com.miiapp.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity android:name="com.trinityimagegcm.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

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

        <service android:name="com.trinityimagegcm.GCMNotificationIntentService" />
    </application>

</manifest>

Step 3. Open your activity_main.xml file inside res ⇒ layout and copy paste below code here i create two button first button help to register your app with google server and get GCM ID, and second button pull that GCM ID to server.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    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.trinityimagegcm.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="registerInBackground"
        android:text="Register to GCM" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="uploadToServer"
        android:text="Save id to server" />
</LinearLayout>

Step 4. Now open your MainActivity.java file add below code in it here we register user with Google GCM server.

package com.trinityimagegcm;

import android.app.NotificationManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

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

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements GetResponse {

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    public static String TAG = "Mainactivity";
    public static final String REG_ID = "regId";
    String regId, msg;
    SharedPreferences prefs;
    GoogleCloudMessaging gcm;
    Context context = this;
    private AsyncReuse requestServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gcm = GoogleCloudMessaging.getInstance(this);
        prefs = getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        regId = getRegistrationId();
    }

    private String getRegistrationId() {
        String registrationId = prefs.getString(REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        return registrationId;
    }

    private void saveRegisterId(Context context, String regId) {
        SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
        Log.i(TAG, "Saving regId on app version ");
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(REG_ID, regId);
        editor.commit();
    }

    public void uploadToServer(View view) {
        JSONObject jObject = new JSONObject();
        executeServerReq();
        try {
            jObject.put("reg", regId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        requestServer.getObjectQ(jObject);
        requestServer.execute();
    }

    private void executeServerReq() {
        requestServer = new AsyncReuse("http://demo.trinitytuts.com/push/saveid.php", true, MainActivity.this);
        requestServer.getResponse = this;
    }

    public void registerInBackground(View view) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regId = gcm.register("260680606263");
                    Log.d("RegisterActivity", "registerInBackground - regId: "
                            + regId);
                    msg = "Device registered, registration ID=" + regId;

                } catch (IOException ex) {
                    msg = "Error :" + ex.getMessage();
                    Log.d("RegisterActivity", "Error: " + msg);
                }
                Log.d("RegisterActivity", "AsyncTask completed: " + msg);
                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                Toast.makeText(getApplicationContext(), "Registered with GCM Server." + msg, Toast.LENGTH_LONG)
                        .show();
                saveRegisterId(context, regId);
            }
        }.execute(null, null, null);
    }

    @Override
    public Void getData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data.toString());
            Log.e("here", "==========" + jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Step 5. Now create receiver

package com.trinityimagegcm;

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

/**
 * Created by aneh on 2/23/2016.
 */
public class GcmReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(), GCMNotificationIntentService.class.getName());
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

Step 6. Now create new new java class and name it GCMNotificationIntentService.java this class show notification and also load image from server and show it in notification bar.

package com.trinityimagegcm;

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.Bundle;
import android.support.v4.app.NotificationCompat;

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

import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by aneh on 2/23/2016.
 */
public class GCMNotificationIntentService extends IntentService {

    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    public static String TAG = "GCMNotificationIntentService";
    Bitmap Images;
    String message;

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


    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);


        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            sendNotification((String) extras.get("msg"));
            }
        }
        GcmReceiver.completeWakefulIntent(intent);
    }


    private void sendNotification(String msg) {

        try {
            JSONObject jsonObject = new JSONObject(msg);
            Images = getBitmapFromURL(jsonObject.getString("image"));
            message = jsonObject.getString("msg");
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

        Intent in = new Intent(this, MainActivity.class);
        in.putExtra("Notif", message);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                in, 0);

        int numMessages = 0;
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                /*.setStyle(new NotificationCompat.BigTextStyle().bigText("dfds"))*/
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(Images))
                .setAutoCancel(true)
                .setContentText(message)
                .setNumber(++numMessages);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    }

    public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

this method show notification with image and also read image URL from json string

private void sendNotification(String msg) {

        try {
            JSONObject jsonObject = new JSONObject(msg);
            Images = getBitmapFromURL(jsonObject.getString("image"));
            message = jsonObject.getString("msg");
        } catch (JSONException e) {
            e.printStackTrace();
        }

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

        Intent in = new Intent(this, MainActivity.class);
        in.putExtra("Notif", message);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                in, 0);

        int numMessages = 0;
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.app_name))
                /*.setStyle(new NotificationCompat.BigTextStyle().bigText("dfds"))*/
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(Images))
                .setAutoCancel(true)
                .setContentText(message)
                .setNumber(++numMessages);
        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

    }

Below method load image from URL we get from GCM and convert it to bitmap.

public static Bitmap getBitmapFromURL(String src) {
        try {
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

For complete code please follow above download link. Hope this will help you.