com.stikyhive.gcm.MyGcmListenerService.java Source code

Java tutorial

Introduction

Here is the source code for com.stikyhive.gcm.MyGcmListenerService.java

Source

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.stikyhive.gcm;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.stikyhive.stikyhive.ChattingActivity;
import com.stikyhive.stikyhive.DBHelper;
import com.stikyhive.stikyhive.JsonWebService;
import com.stikyhive.stikyhive.R;
import com.stikyhive.stikyhive.StikyChatMoreActivity;
import com.google.android.gms.gcm.GcmListenerService;

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

import java.util.List;

public class MyGcmListenerService extends GcmListenerService {

    public static boolean flagSendNoti;
    private static final String TAG = "MyGcmListenerService";
    public static String msg;
    private String recipientStkid, chatRecipient, senderToken, recipientToken, stkidCheck, fileName;
    private String chatRecipientUrl;
    private JsonWebService ws;
    private SharedPreferences sharedPreferences;
    private DBHelper dbHelper;
    private static boolean flagNoti;

    /**
     * Called when message is received.
     *
     * @param from SenderID of the sender.
     * @param data Data bundle containing message data as key/value pairs.
     *             For Set of keys use data.keySet().
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(String from, Bundle data) {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        ws = new JsonWebService();
        dbHelper = new DBHelper(getApplicationContext());
        fileName = data.getString("fileName");
        String message = data.getString("message");
        this.msg = data.getString("msg");
        int offerId = Integer.parseInt(data.getString("offerId"));
        int offerStatus = Integer.parseInt(data.getString("offerStatus"));
        String price = data.getString("price");
        String rate = data.getString("rate");
        String name = data.getString("name");
        recipientStkid = data.getString("recipientStkid");
        stkidCheck = sharedPreferences.getString("stkid", "");
        chatRecipient = data.getString("chatRecipient");
        chatRecipientUrl = data.getString("chatRecipientUrl");
        senderToken = data.getString("senderToken");
        recipientToken = data.getString("recipientToken");
        ChattingActivity.firstConnect = true;
        Log.i(TAG, "recipient url : " + chatRecipientUrl);
        Log.i(TAG, "Message: " + message);
        //this.message = message;
        Log.i(TAG, "msg " + message);
        sharedPreferences.edit().putString("fileName", fileName).apply();
        sharedPreferences.edit().putString("message", message).apply();
        sharedPreferences.edit().putInt("offerId", offerId).apply();
        sharedPreferences.edit().putInt("offerStatus", offerStatus).apply();
        sharedPreferences.edit().putString("price", price).apply();
        sharedPreferences.edit().putString("rate", rate).apply();
        sharedPreferences.edit().putString("name", name).apply();
        sharedPreferences.edit().putString("chatRecipientUrl", chatRecipientUrl).apply();
        sharedPreferences.edit().putString("recipientStkid", recipientStkid).apply();
        sharedPreferences.edit().putString("chatRecipientName", chatRecipient).apply();
        sharedPreferences.edit().putString("stkidCheck", stkidCheck).apply();
        sharedPreferences.edit().putString("senderToken", senderToken).apply();
        // sharedPreferences.edit().putString("recipientToken", recipientToken).apply();

        // Notify UI that registration has completed, so the progress indicator can be hidden.
        /*Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);*/
        //sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();

        /**
         * Production applications would usually process the message here.
         * Eg: - Syncing with server.
         *     - Store message in local database.
         *     - Update UI.
         */

        /**
         * In some cases it may be useful to show a notification indicating to the user
         * that a message was received.
         */
        if (!checkApp()) {
            sendNotification(message);
        }
    }

    public boolean checkApp() {
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);

        // get the info from the currently running task
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

        //        ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        //        List<ActivityManager.RunningTaskInfo> services = activityManager
        //                .getRunningTasks(Integer.MAX_VALUE);

        ComponentName componentInfo = taskInfo.get(0).topActivity;
        Log.i("Package Activity", " " + componentInfo.getPackageName());
        Log.i("Class Activity", " " + componentInfo.getClassName());
        if (componentInfo.getClassName().equalsIgnoreCase("com.stikyhive.stikyhive.StikyChatMoreActivity")) {
            Log.i(TAG, "Chat More Activity");
            StikyChatMoreActivity.flagGCM = true;
            flagNoti = false;
            Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
            return false;
        } else if (componentInfo.getClassName().equalsIgnoreCase("com.stikyhive.stikyhive.ChattingActivity")) {
            Log.i("TAG", componentInfo.getClass() + " ");
            Intent registrationComplete = new Intent(QuickstartPreferences.CHAT_REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
            return true;
        } else if (componentInfo.getPackageName() != "com.stikyhive.stikyhive") {
            flagNoti = true;
            return false;
        } else {
            flagNoti = false;
            return false;
        }
    }

    // [END receive_message]

    /**
     * Create and show a simple notification containing the received GCM message.
     *
     * @param message GCM message received.
     */
    public void sendNotification(String message) {
        //Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
        // LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
        Log.i(TAG, " notification ");
        new regTask().execute("Messages");
        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    }

    final class regTask extends AsyncTask<Object, Object, Object> {
        JSONObject objMessages, objChatMore;
        int rows = 0;

        @Override
        protected void onPreExecute() {
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(Object result) {
            Log.d("ending", "ending");
            super.onPostExecute(result);

            try {
                if (objMessages != null) {
                    if (objMessages.getString("status").toString().equals("success")) {
                        dbHelper.deleteStikyChat();
                        JSONArray jsonArr = objMessages.getJSONArray("messages");
                        for (int i = 0; i < jsonArr.length(); i++) {
                            JSONObject json = jsonArr.getJSONObject(i);
                            int id = json.getInt("id");
                            String fromStikyBee = json.getString("fromStikyBee");
                            String toStikyBee = json.getString("toStikyBee");
                            String message = json.getString("message");
                            String createDate = json.getString("createDate");
                            String fileName = json.getString("fileName");
                            int offerId = 0, offerStatus = 0, skillId = 0;
                            String price = null, rate = null, name = null;
                            if (json.getString("offerId") != "null") {
                                offerId = json.getInt("offerId");
                                offerStatus = json.getInt("offerStatus");
                                skillId = json.getInt("skillId");
                                price = json.getString("price");
                                rate = json.getString("rate");
                                name = json.getString("name");
                            }
                            Log.i("Chatting createDate : ", " *" + createDate);
                            dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate, offerId,
                                    offerStatus, skillId, price, rate, name, fileName);
                        }
                        rows = objMessages.getInt("rows");

                    } else {

                    }
                    Log.i(TAG, " &&& " + recipientStkid + " : " + chatRecipient + " : " + chatRecipientUrl + " : "
                            + recipientToken + " : " + senderToken + " : " + msg + " : " + rows);
                    Intent intent = new Intent("com.arctech.CHATTING");
                    intent.putExtra("recipientStkid", recipientStkid);
                    intent.putExtra("chatRecipient", chatRecipient);
                    intent.putExtra("chatRecipientUrl", chatRecipientUrl);
                    intent.putExtra("senderToken", recipientToken);
                    intent.putExtra("recipientToken", senderToken);
                    intent.putExtra("noti", flagNoti);
                    intent.putExtra("message", msg);
                    intent.putExtra("rows", rows);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

                    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    int requestID = (int) System.currentTimeMillis();

                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
                            requestID /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);

                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                            getApplicationContext()).setSmallIcon(R.drawable.ic_launcher)
                                    .setContentTitle("StikyHive Message").setContentText(msg).setAutoCancel(true)
                                    .setSound(defaultSoundUri).setContentIntent(pendingIntent);

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

                    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        protected Object doInBackground(Object... arg0) {
            // TODO Auto-generated method stub

            try {

                objMessages = sendcodeService();

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    }

    /**
     * @return JSONObject
     * @throws JSONException
     */
    public JSONObject sendcodeService() throws JSONException {

        JSONObject objTemp = null;
        String url2 = "/androidstikyhive/index.php/api/users/selectChatMsgs/format/json";

        try {
            JSONObject obj = new JSONObject();

            obj.put("fromStikyBee", sharedPreferences.getString("stkid", ""));
            obj.put("toStikyBee", recipientStkid);
            obj.put("limit", 7);

            objTemp = ws.insertORupdateObj(this.getResources().getString(R.string.url), url2, obj);

        } catch (Exception e) {
            // TODO: handle exception

        } finally {

        }
        return objTemp;
    }

}