master b6dce4a8b153 cached
22 files
27.0 KB
8.0k tokens
16 symbols
1 requests
Download .txt
Repository: jirawatee/FirebaseCloudMessaging-Android
Branch: master
Commit: b6dce4a8b153
Files: 22
Total size: 27.0 KB

Directory structure:
gitextract_wv0ejhht/

├── .gitignore
├── README.md
├── app/
│   ├── .gitignore
│   ├── build.gradle
│   ├── proguard-rules.pro
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── com/
│           │       └── example/
│           │           └── fcm/
│           │               ├── MainActivity.java
│           │               ├── MyFirebaseMessagingService.java
│           │               └── SecondActivity.java
│           └── res/
│               ├── layout/
│               │   ├── activity_main.xml
│               │   └── activity_second.xml
│               └── values/
│                   ├── colors.xml
│                   ├── dimens.xml
│                   ├── strings.xml
│                   └── styles.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
#built application files
*.apk
*.ap_

# files for the dex VM
*.dex

# Java class files
*.class

# generated files
bin/
gen/
out/

# Local configuration file (sdk path, etc)
local.properties

# Windows thumbnail db
Thumbs.db

# OSX files
.DS_Store

# Log Files
*.log

# Android Studio
*.iml
.gradle/
build/
captures/
.navigation/

# Intellij IDEA
.idea/

# Eclipse project files
.classpath
.project

# Proguard folder generated by Eclipse
proguard/

# Eclipse Metadata
.metadata/

# Keystore files
*.jks

.externalNativeBuild

google-services.json

================================================
FILE: README.md
================================================
# Firebase Cloud Messaging (FCM)
FCM is just a demo of Android Application which implement Firebase Cloud Messaging. It made for Google I/O Extended 2016 Bangkok 

## Prerequisites
* Supported Android 4.1 or newer
* Android Studio 3.3.2 or higher
* google-services.json in app-level folder

## Features
* Subscribe and Unsubscribe with topics
* Get token
* Send message with payload both **notification** and **data**
* Send message with **a token**, **token group**, **a topic**, **condition**
* Handle message both **foreground** and **background**
* Customize notification
* Support notification channel for Android 0 or newer

## Limitation in the message payload
* Notification : 2KB limit and a predefined set of user-visible keys
* Data : 4KB of custom key-value pairs

## Screenshots
<table width="100%">
	<tr>
	  <th width="33%"><img src="https://cloud.githubusercontent.com/assets/1763410/16547014/9f81c04a-4187-11e6-936c-0d901d91b8e5.png"></th>
	  <th width="33%"><img src="https://cloud.githubusercontent.com/assets/1763410/16553886/8f8af5da-41f5-11e6-85c4-cb6937c80bab.png"></th>
	  <th width="33%"><img src="https://cloud.githubusercontent.com/assets/1763410/16553891/97fa1d18-41f5-11e6-9f53-e76a61e9b435.png"></th>
	</tr>
</table>

## Slide
```FCM
https://docs.google.com/presentation/d/1HPLk1PXaGUjqTlPB6RHsgrTunJNo10kbGZ-JX_7JELw/edit?usp=sharing
```


================================================
FILE: app/.gitignore
================================================
/build


================================================
FILE: app/build.gradle
================================================
apply plugin: 'com.android.application'

android {
	compileSdkVersion compileAndTargetSdkVersion
	buildToolsVersion '30.0.3'

	defaultConfig {
		applicationId "com.example.fcm"
		minSdkVersion 21
		targetSdkVersion compileAndTargetSdkVersion
		versionCode 1
		versionName "1.0"
		resConfigs('en', 'xxxhdpi')
		ndk {
			abiFilters "x86", "x86_64", "arm64-v8a", "armeabi-v7a"
		}
	}

	buildTypes {
		release {
			minifyEnabled true
			shrinkResources true
			proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
		}
		debug {
			splits.abi.enable = false
			splits.density.enable = false
			aaptOptions.cruncherEnabled = false
		}
	}

	dexOptions {
		preDexLibraries true
		maxProcessCount 8
	}
}

dependencies {
	implementation 'androidx.appcompat:appcompat:1.2.0'
	implementation 'com.google.firebase:firebase-analytics:18.0.3'
	implementation 'com.google.firebase:firebase-messaging:21.1.0'
}

apply plugin: 'com.google.gms.google-services'

================================================
FILE: app/proguard-rules.pro
================================================
-keepattributes Signature
-keepattributes *Annotation*
-keepattributes EnclosingMethod
-keepattributes InnerClasses

-assumenosideeffects class android.util.Log {
    public static boolean isLoggable(java.lang.String, int);
    public static int v(...);
    public static int i(...);
    public static int w(...);
    public static int d(...);
    public static int e(...);
    public static int wtf(...);
}

================================================
FILE: app/src/main/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.fcm"
		  xmlns:android="http://schemas.android.com/apk/res/android"
		  android:installLocation="auto">

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

		<meta-data
			android:name="com.google.firebase.messaging.default_notification_channel_id"
			android:value="@string/notification_channel_id" />

		<meta-data
			android:name="com.google.firebase.messaging.default_notification_icon"
			android:resource="@drawable/ic_notification" />

		<meta-data
			android:name="com.google.firebase.messaging.default_notification_color"
			android:resource="@color/colorAccent" />

		<service
			android:name=".MyFirebaseMessagingService"
			android:exported="false">
			<intent-filter>
				<action android:name="com.google.firebase.MESSAGING_EVENT"/>
			</intent-filter>
		</service>

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

		<activity android:name=".SecondActivity">
			<intent-filter>
				<action android:name="OPEN_ACTIVITY_1"/>
				<category android:name="android.intent.category.DEFAULT"/>
			</intent-filter>
		</activity>

	</application>

</manifest>

================================================
FILE: app/src/main/java/com/example/fcm/MainActivity.java
================================================
package com.example.fcm;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;

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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

import static com.example.fcm.R.id.txt;

public class MainActivity extends AppCompatActivity {
	private static final String AUTH_KEY = "key=YOUR-SERVER-KEY";
	private TextView mTextView;
	private String token;

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

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String tmp = "";
			for (String key : bundle.keySet()) {
				Object value = bundle.get(key);
				tmp += key + ": " + value + "\n\n";
			}
			mTextView.setText(tmp);
		}

		FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
			@Override
			public void onComplete(@NonNull Task<InstanceIdResult> task) {
				if (!task.isSuccessful()) {
					token = task.getException().getMessage();
					Log.w("FCM TOKEN Failed", task.getException());
				} else {
					token = task.getResult().getToken();
					Log.i("FCM TOKEN", token);
				}
			}
		});
	}

	public void showToken(View view) {
		mTextView.setText(token);
	}

	public void subscribe(View view) {
		FirebaseMessaging.getInstance().subscribeToTopic("news");
		mTextView.setText(R.string.subscribed);
	}

	public void unsubscribe(View view) {
		FirebaseMessaging.getInstance().unsubscribeFromTopic("news");
		mTextView.setText(R.string.unsubscribed);
	}

	public void sendToken(View view) {
		sendWithOtherThread("token");
	}

	public void sendTokens(View view) {
		sendWithOtherThread("tokens");
	}

	public void sendTopic(View view) {
		sendWithOtherThread("topic");
	}

	private void sendWithOtherThread(final String type) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				pushNotification(type);
			}
		}).start();
	}

	private void pushNotification(String type) {
		JSONObject jPayload = new JSONObject();
		JSONObject jNotification = new JSONObject();
		JSONObject jData = new JSONObject();
		try {
			jNotification.put("title", "Google I/O 2016");
			jNotification.put("body", "Firebase Cloud Messaging (App)");
			jNotification.put("sound", "default");
			jNotification.put("badge", "1");
			jNotification.put("click_action", "OPEN_ACTIVITY_1");
			jNotification.put("icon", "ic_notification");

			jData.put("picture", "https://miro.medium.com/max/1400/1*QyVPcBbT_jENl8TGblk52w.png");

			switch(type) {
				case "tokens":
					JSONArray ja = new JSONArray();
					ja.put("c5pBXXsuCN0:APA91bH8nLMt084KpzMrmSWRS2SnKZudyNjtFVxLRG7VFEFk_RgOm-Q5EQr_oOcLbVcCjFH6vIXIyWhST1jdhR8WMatujccY5uy1TE0hkppW_TSnSBiUsH_tRReutEgsmIMmq8fexTmL");
					ja.put(token);
					jPayload.put("registration_ids", ja);
					break;
				case "topic":
					jPayload.put("to", "/topics/news");
					break;
				case "condition":
					jPayload.put("condition", "'sport' in topics || 'news' in topics");
					break;
				default:
					jPayload.put("to", token);
			}

			jPayload.put("priority", "high");
			jPayload.put("notification", jNotification);
			jPayload.put("data", jData);

			URL url = new URL("https://fcm.googleapis.com/fcm/send");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Authorization", AUTH_KEY);
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setDoOutput(true);

			// Send FCM message content.
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(jPayload.toString().getBytes());

			// Read FCM response.
			InputStream inputStream = conn.getInputStream();
			final String resp = convertStreamToString(inputStream);

			Handler h = new Handler(Looper.getMainLooper());
			h.post(new Runnable() {
				@Override
				public void run() {
					mTextView.setText(resp);
				}
			});
		} catch (JSONException | IOException e) {
			e.printStackTrace();
		}
	}

	private String convertStreamToString(InputStream is) {
		Scanner s = new Scanner(is).useDelimiter("\\A");
		return s.hasNext() ? s.next().replace(",", ",\n") : "";
	}
}

================================================
FILE: app/src/main/java/com/example/fcm/MyFirebaseMessagingService.java
================================================
package com.example.fcm;

import android.app.Notification;
import android.app.NotificationChannel;
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.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
	public static final String FCM_PARAM = "picture";
	private static final String CHANNEL_NAME = "FCM";
	private static final String CHANNEL_DESC = "Firebase Cloud Messaging";
	private int numMessages = 0;

	@Override
	public void onMessageReceived(RemoteMessage remoteMessage) {
		super.onMessageReceived(remoteMessage);
		RemoteMessage.Notification notification = remoteMessage.getNotification();
		Map<String, String> data = remoteMessage.getData();
		Log.d("FROM", remoteMessage.getFrom());
		sendNotification(notification, data);
	}

	private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
		Bundle bundle = new Bundle();
		bundle.putString(FCM_PARAM, data.get(FCM_PARAM));

		Intent intent = new Intent(this, SecondActivity.class);
		intent.putExtras(bundle);

		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getString(R.string.notification_channel_id))
				.setContentTitle(notification.getTitle())
				.setContentText(notification.getBody())
				.setAutoCancel(true)
				.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
				//.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.win))
				.setContentIntent(pendingIntent)
				.setContentInfo("Hello")
				.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
				.setColor(getColor(R.color.colorAccent))
				.setLights(Color.RED, 1000, 300)
				.setDefaults(Notification.DEFAULT_VIBRATE)
				.setNumber(++numMessages)
				.setSmallIcon(R.drawable.ic_notification);

		try {
			String picture = data.get(FCM_PARAM);
			if (picture != null && !"".equals(picture)) {
				URL url = new URL(picture);
				Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
				notificationBuilder.setStyle(
						new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
				);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

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

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel(
					getString(R.string.notification_channel_id), CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT
			);
			channel.setDescription(CHANNEL_DESC);
			channel.setShowBadge(true);
			channel.canShowBadge();
			channel.enableLights(true);
			channel.setLightColor(Color.RED);
			channel.enableVibration(true);
			channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});

			assert notificationManager != null;
			notificationManager.createNotificationChannel(channel);
		}

		assert notificationManager != null;
		notificationManager.notify(0, notificationBuilder.build());
	}
}

================================================
FILE: app/src/main/java/com/example/fcm/SecondActivity.java
================================================
package com.example.fcm;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);

		TextView txt = findViewById(R.id.textView);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			for (String key : bundle.keySet()) {
				Object value = bundle.get(key);
				txt.append(key + ": " + value + "\n\n");
			}
		}
	}
}

================================================
FILE: app/src/main/res/layout/activity_main.xml
================================================
<?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.example.fcm.MainActivity">

	<ImageView
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_above="@+id/zoneCenter"
		android:layout_centerHorizontal="true"
		android:layout_margin="@dimen/activity_horizontal_margin"
		android:contentDescription="@string/app_name"
		android:src="@mipmap/fcm"/>

	<LinearLayout
		android:id="@+id/zoneCenter"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_centerInParent="true"
		android:orientation="vertical">

		<Button
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:onClick="showToken"
			android:text="@string/btn_show_token"/>

		<LinearLayout
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:orientation="horizontal"
			android:paddingBottom="@dimen/activity_vertical_margin"
			android:paddingTop="@dimen/activity_vertical_margin">

			<Button
				style="@style/CustomButton"
				android:text="@string/btn_subscribe_news"
				android:onClick="subscribe"/>

			<Button
				style="@style/CustomButton"
				android:text="@string/btn_unsubscribe_news"
				android:onClick="unsubscribe"/>

		</LinearLayout>

		<LinearLayout
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:orientation="horizontal">

			<Button
				style="@style/CustomButton"
				android:text="@string/btn_send_token"
				android:onClick="sendToken"/>

			<Button
				style="@style/CustomButton"
				android:text="@string/btn_send_tokens"
				android:onClick="sendTokens"/>

			<Button
				style="@style/CustomButton"
				android:text="@string/btn_send_topic"
				android:onClick="sendTopic"/>

		</LinearLayout>

	</LinearLayout>

	<TextView
		android:id="@+id/txt"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_below="@id/zoneCenter"
		android:paddingBottom="@dimen/activity_vertical_margin"
		android:paddingTop="@dimen/activity_vertical_margin"
		android:gravity="center"
		android:text="@string/result"/>

</RelativeLayout>


================================================
FILE: app/src/main/res/layout/activity_second.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	android:id="@+id/activity_second"
	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:paddingTop="@dimen/activity_vertical_margin"
	android:paddingLeft="@dimen/activity_horizontal_margin"
	android:paddingRight="@dimen/activity_horizontal_margin"
	tools:context="com.example.fcm.SecondActivity">

	<TextView
		android:id="@+id/textView"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerInParent="true"/>

</RelativeLayout>

================================================
FILE: app/src/main/res/values/colors.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<color name="colorPrimary">#039be5</color>
	<color name="colorPrimaryDark">#0288d1</color>
	<color name="colorAccent">#fb8c00</color>
</resources>

================================================
FILE: app/src/main/res/values/dimens.xml
================================================
<resources>
	<!-- Default screen margins, per the Android Design guidelines. -->
	<dimen name="activity_horizontal_margin">16dp</dimen>
	<dimen name="activity_vertical_margin">16dp</dimen>

</resources>


================================================
FILE: app/src/main/res/values/strings.xml
================================================
<resources>
	<string name="app_name">FCM</string>
	<string name="btn_send_token">Send Token</string>
	<string name="btn_send_tokens">Send Tokens</string>
	<string name="btn_send_topic">Send Topic</string>
	<string name="btn_show_token">Show Token</string>
	<string name="btn_subscribe_news">Subscribe (News)</string>
	<string name="btn_unsubscribe_news">Unsubscribe (News)</string>
	<string name="notification_channel_id">default</string>
	<string name="result">Something will happen here&#8230;</string>
	<string name="subscribed">Subscribed to news topic</string>
	<string name="unsubscribed">Unsubscribed from news topic</string>
</resources>

================================================
FILE: app/src/main/res/values/styles.xml
================================================
<resources>

	<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
		<!-- Customize your theme here. -->
		<item name="colorPrimary">@color/colorPrimary</item>
		<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
		<item name="colorAccent">@color/colorAccent</item>
	</style>

	<style name="CustomButton">
		<item name="android:layout_width">0dp</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:layout_weight">1</item>
	</style>

</resources>


================================================
FILE: build.gradle
================================================
buildscript {
	repositories {
		google()
		jcenter()
		mavenCentral()
	}
	dependencies {
		classpath 'com.android.tools.build:gradle:4.1.3'
		classpath 'com.google.gms:google-services:4.3.5'
	}
}

allprojects {
	repositories {
		google()
		jcenter()
		mavenCentral()
	}
}

task clean(type: Delete) {
	delete rootProject.buildDir
}

ext {
	compileAndTargetSdkVersion = 30
}

================================================
FILE: gradle/wrapper/gradle-wrapper.properties
================================================
#Thu May 18 21:45:47 ICT 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-all.zip


================================================
FILE: gradle.properties
================================================
# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
android.enableJetifier=true
android.useAndroidX=true

================================================
FILE: gradlew
================================================
#!/usr/bin/env bash

##############################################################################
##
##  Gradle start up script for UN*X
##
##############################################################################

# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""

APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`

# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"

warn ( ) {
    echo "$*"
}

die ( ) {
    echo
    echo "$*"
    echo
    exit 1
}

# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
  CYGWIN* )
    cygwin=true
    ;;
  Darwin* )
    darwin=true
    ;;
  MINGW* )
    msys=true
    ;;
esac

# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG=`dirname "$PRG"`"/$link"
    fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null

CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar

# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
        # IBM's JDK on AIX uses strange locations for the executables
        JAVACMD="$JAVA_HOME/jre/sh/java"
    else
        JAVACMD="$JAVA_HOME/bin/java"
    fi
    if [ ! -x "$JAVACMD" ] ; then
        die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
    fi
else
    JAVACMD="java"
    which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi

# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
    MAX_FD_LIMIT=`ulimit -H -n`
    if [ $? -eq 0 ] ; then
        if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
            MAX_FD="$MAX_FD_LIMIT"
        fi
        ulimit -n $MAX_FD
        if [ $? -ne 0 ] ; then
            warn "Could not set maximum file descriptor limit: $MAX_FD"
        fi
    else
        warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
    fi
fi

# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
    GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
    APP_HOME=`cygpath --path --mixed "$APP_HOME"`
    CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
    JAVACMD=`cygpath --unix "$JAVACMD"`

    # We build the pattern for arguments to be converted via cygpath
    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
    SEP=""
    for dir in $ROOTDIRSRAW ; do
        ROOTDIRS="$ROOTDIRS$SEP$dir"
        SEP="|"
    done
    OURCYGPATTERN="(^($ROOTDIRS))"
    # Add a user-defined pattern to the cygpath arguments
    if [ "$GRADLE_CYGPATTERN" != "" ] ; then
        OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
    fi
    # Now convert the arguments - kludge to limit ourselves to /bin/sh
    i=0
    for arg in "$@" ; do
        CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
        CHECK2=`echo "$arg"|egrep -c "^-"`                                 ### Determine if an option

        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition
            eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
        else
            eval `echo args$i`="\"$arg\""
        fi
        i=$((i+1))
    done
    case $i in
        (0) set -- ;;
        (1) set -- "$args0" ;;
        (2) set -- "$args0" "$args1" ;;
        (3) set -- "$args0" "$args1" "$args2" ;;
        (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
        (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
        (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
        (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
        (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
        (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
    esac
fi

# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
    JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"


================================================
FILE: gradlew.bat
================================================
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem  Gradle startup script for Windows
@rem
@rem ##########################################################################

@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal

@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=

set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%

@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome

set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init

echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe

if exist "%JAVA_EXE%" goto init

echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.

goto fail

:init
@rem Get command-line arguments, handling Windowz variants

if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args

:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2

:win9xME_args_slurp
if "x%~1" == "x" goto execute

set CMD_LINE_ARGS=%*
goto execute

:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$

:execute
@rem Setup the command line

set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar

@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%

:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd

:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if  not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1

:mainEnd
if "%OS%"=="Windows_NT" endlocal

:omega


================================================
FILE: settings.gradle
================================================
include ':app'
Download .txt
gitextract_wv0ejhht/

├── .gitignore
├── README.md
├── app/
│   ├── .gitignore
│   ├── build.gradle
│   ├── proguard-rules.pro
│   └── src/
│       └── main/
│           ├── AndroidManifest.xml
│           ├── java/
│           │   └── com/
│           │       └── example/
│           │           └── fcm/
│           │               ├── MainActivity.java
│           │               ├── MyFirebaseMessagingService.java
│           │               └── SecondActivity.java
│           └── res/
│               ├── layout/
│               │   ├── activity_main.xml
│               │   └── activity_second.xml
│               └── values/
│                   ├── colors.xml
│                   ├── dimens.xml
│                   ├── strings.xml
│                   └── styles.xml
├── build.gradle
├── gradle/
│   └── wrapper/
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
Download .txt
SYMBOL INDEX (16 symbols across 3 files)

FILE: app/src/main/java/com/example/fcm/MainActivity.java
  class MainActivity (line 32) | public class MainActivity extends AppCompatActivity {
    method onCreate (line 37) | @Override
    method showToken (line 67) | public void showToken(View view) {
    method subscribe (line 71) | public void subscribe(View view) {
    method unsubscribe (line 76) | public void unsubscribe(View view) {
    method sendToken (line 81) | public void sendToken(View view) {
    method sendTokens (line 85) | public void sendTokens(View view) {
    method sendTopic (line 89) | public void sendTopic(View view) {
    method sendWithOtherThread (line 93) | private void sendWithOtherThread(final String type) {
    method pushNotification (line 102) | private void pushNotification(String type) {
    method convertStreamToString (line 164) | private String convertStreamToString(InputStream is) {

FILE: app/src/main/java/com/example/fcm/MyFirebaseMessagingService.java
  class MyFirebaseMessagingService (line 25) | public class MyFirebaseMessagingService extends FirebaseMessagingService {
    method onMessageReceived (line 31) | @Override
    method sendNotification (line 40) | private void sendNotification(RemoteMessage.Notification notification,...

FILE: app/src/main/java/com/example/fcm/SecondActivity.java
  class SecondActivity (line 7) | public class SecondActivity extends AppCompatActivity {
    method onCreate (line 8) | @Override
Condensed preview — 22 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (31K chars).
[
  {
    "path": ".gitignore",
    "chars": 546,
    "preview": "#built application files\n*.apk\n*.ap_\n\n# files for the dex VM\n*.dex\n\n# Java class files\n*.class\n\n# generated files\nbin/\ng"
  },
  {
    "path": "README.md",
    "chars": 1368,
    "preview": "# Firebase Cloud Messaging (FCM)\nFCM is just a demo of Android Application which implement Firebase Cloud Messaging. It "
  },
  {
    "path": "app/.gitignore",
    "chars": 7,
    "preview": "/build\n"
  },
  {
    "path": "app/build.gradle",
    "chars": 980,
    "preview": "apply plugin: 'com.android.application'\n\nandroid {\n\tcompileSdkVersion compileAndTargetSdkVersion\n\tbuildToolsVersion '30."
  },
  {
    "path": "app/proguard-rules.pro",
    "chars": 407,
    "preview": "-keepattributes Signature\n-keepattributes *Annotation*\n-keepattributes EnclosingMethod\n-keepattributes InnerClasses\n\n-as"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "chars": 1466,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest package=\"com.example.fcm\"\n\t\t  xmlns:android=\"http://schemas.android.com"
  },
  {
    "path": "app/src/main/java/com/example/fcm/MainActivity.java",
    "chars": 4836,
    "preview": "package com.example.fcm;\n\nimport android.os.Bundle;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android."
  },
  {
    "path": "app/src/main/java/com/example/fcm/MyFirebaseMessagingService.java",
    "chars": 3705,
    "preview": "package com.example.fcm;\n\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.No"
  },
  {
    "path": "app/src/main/java/com/example/fcm/SecondActivity.java",
    "chars": 586,
    "preview": "package com.example.fcm;\n\nimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.widg"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "chars": 2579,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n\txmlns:android=\"http://schemas.android.com/apk/res/android\"\n\txmln"
  },
  {
    "path": "app/src/main/res/layout/activity_second.xml",
    "chars": 725,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n\tandroid:id=\"@+id/activity_second\"\n\txmlns:android=\"http://schemas"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "chars": 198,
    "preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n\t<color name=\"colorPrimary\">#039be5</color>\n\t<color name=\"colorPrimar"
  },
  {
    "path": "app/src/main/res/values/dimens.xml",
    "chars": 203,
    "preview": "<resources>\n\t<!-- Default screen margins, per the Android Design guidelines. -->\n\t<dimen name=\"activity_horizontal_margi"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "chars": 645,
    "preview": "<resources>\n\t<string name=\"app_name\">FCM</string>\n\t<string name=\"btn_send_token\">Send Token</string>\n\t<string name=\"btn_"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "chars": 506,
    "preview": "<resources>\n\n\t<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n\t\t<!-- Customize your theme here. -->"
  },
  {
    "path": "build.gradle",
    "chars": 372,
    "preview": "buildscript {\n\trepositories {\n\t\tgoogle()\n\t\tjcenter()\n\t\tmavenCentral()\n\t}\n\tdependencies {\n\t\tclasspath 'com.android.tools."
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "chars": 230,
    "preview": "#Thu May 18 21:45:47 ICT 2017\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_"
  },
  {
    "path": "gradle.properties",
    "chars": 908,
    "preview": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will o"
  },
  {
    "path": "gradlew",
    "chars": 4971,
    "preview": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start "
  },
  {
    "path": "gradlew.bat",
    "chars": 2404,
    "preview": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@r"
  },
  {
    "path": "settings.gradle",
    "chars": 15,
    "preview": "include ':app'\n"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the jirawatee/FirebaseCloudMessaging-Android GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 22 files (27.0 KB), approximately 8.0k tokens, and a symbol index with 16 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!