com.arctech.gcm.MyGcmListenerService.java Source code

Java tutorial

Introduction

Here is the source code for com.arctech.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.arctech.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.arctech.stikyhive.ChattingActivity;
import com.arctech.stikyhive.DBHelper;
import com.arctech.stikyhive.JsonWebService;
import com.arctech.stikyhive.R;
import com.arctech.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 message;
    private String recipientStkid, chatRecipient, senderToken, recipientToken, stkidCheck;
    private String chatRecipientUrl;
    private JsonWebService ws;
    private SharedPreferences sharedPreferences;
    private DBHelper dbHelper;
    private 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(this);
        ws = new JsonWebService();
        dbHelper = new DBHelper(this);

        String message = data.getString("message");
        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("message", message).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) this.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.arctech.stikyhive.StikyChatMoreActivity")) {
            Log.i(TAG, "Chat More Activity");
            StikyChatMoreActivity.flagGCM = true;
            flagNoti = false;
            Intent registrationComplete = new Intent(QuickstartPreferences.REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
            return false;
        } else if (componentInfo.getClassName().equalsIgnoreCase("com.arctech.stikyhive.ChattingActivity")) {
            Log.i("TAG", componentInfo.getClass() + " ");
            Intent registrationComplete = new Intent(QuickstartPreferences.CHAT_REGISTRATION_COMPLETE);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
            return true;
        } else if (componentInfo.getPackageName() != "com.arctech.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");
                            Log.i("Chatting createDate : ", " *" + createDate);
                            dbHelper.insertStikyChat(id, fromStikyBee, toStikyBee, message, createDate);
                        }
                        rows = objMessages.getInt("rows");

                    } else {

                    }
                    Log.i(TAG, " &&& " + recipientStkid + " : " + chatRecipient + " : " + chatRecipientUrl + " : "
                            + recipientToken + " : " + senderToken + " : " + message + " : " + 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", message);
                    intent.putExtra("rows", rows);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
                            0 /* Request code */, intent, PendingIntent.FLAG_CANCEL_CURRENT);

                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                            getApplicationContext()).setSmallIcon(R.drawable.ic_launcher)
                                    .setContentTitle("StikyHive Message").setContentText(message)
                                    .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;
    }

}