trying to start a service from a background service, somehow it work with all android version Lower than api 24, and actually not work in (oreo,Pie,..).
however i try this code below, and this screen for problem i face if testing using +api>24....
Error picture
Glade for your help, Thanks!!
1) Main Activity(Start Services) :
public void startService(View v) {
String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", input);
ContextCompat.startForegroundService(this, serviceIntent);
Toast.makeText(Options.this,"Notification, On.", Toast.LENGTH_LONG).show();
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this, ExampleService.class);
stopService(serviceIntent);
Toast.makeText(Options.this,"Notification, Off.", Toast.LENGTH_LONG).show();
}
2) Background services Class :
package com.demo.testttt;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import static com.demo.testttt.App.CHANNEL_ID;
public class ExampleService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, Home.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
}
else {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, Home.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new Notification.Builder(ExampleService.this)
.setVibrate(new long[] { 350, 350})
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.logo)
.setContentIntent(pendingIntent)
.build();
NotificationManager notifmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/// notifmanager.notify(0,notification);
startForeground(1, notification);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
3) App Class :
package package com.demo.testttt;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
4) manifest xml :
<service
android:name=".ExampleService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:enabled="true"
android:exported="true"/>
where is Your Permission in Manifest.
you should permission of FOREGROUND_SERVICE.
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Related
I am making an app that reads data being sent via Bluetooth in one activity which then is redirected to a foreground service which sends an intent to another activity where the data will be processed. I know I am missing something in the code for the broadcast receiver on the activity code.
If anyone can give me advice or help me with the data being able to be processed. There are no crashes so far. I am new in coding in android studio and any help would be great!
*** This is the code for the Foreground Service ***
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate(){
super.onCreate();
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//super.onStartCommand(intent, flags, startId);
String input = intent.getStringExtra("inputExtra");
Log.i("Tag", input);
sendData(input);
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
private void sendData(String input){
Log.i("Tag", "inside sendData");
Intent intent = new Intent();
intent.setAction("com.example.Pillwoah.sendbroadcast");
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("inputExtra", input);
sendBroadcast(intent);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
*** This is the code for the activity ***
public class MainActivity5 extends AppCompatActivity {
protected static final String TAG = "TAG";
TextView dataText;
BroadcastReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
Log.i(TAG, "data sending");
configureReceiver();
}
class DataBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = "Broadcast intent detected " + intent.getAction();
Log.i(TAG, message);
}
}
private void configureReceiver(){
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.Pillwoah.sendbroadcast");
receiver = new DataBroadcastReceiver();
registerReceiver(receiver, filter);
}
}
I want to make an app that shows a notification as soon as headphone is plugged in and remove it when it is plugged out. My app works fine when it is on or home button is pressed, but doesn't work when back is pressed or app is closed by long pressing home and swiping it away. What should I use in order to make it work?
This is my code
package com.example.earphone;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class HeadsetPlugReceiver extends BroadcastReceiver {
TextView t1;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}
boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
// boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");
Log.v("message", "headphone connected" + headsetName);
Intent i = new Intent(context, MainActivity.class);
PendingIntent p = PendingIntent.getActivity(context,0,i,0);
// Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if(state==1){
Intent intent1 = new Intent(context, ES.class);
context.startForegroundService(intent1);
}
switch (state) {
case 0:
Intent intent1 = new Intent(context, ES.class);
context.stopService( intent1);
Toast.makeText(context, "Headphone ejected", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "I have no idea what the headset state is", Toast.LENGTH_SHORT).show();
}
}
}}
package com.example.earphone;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String C_ID = "noti";
#Override
public void onCreate() {
super.onCreate();
createnoti();
}
private void createnoti(){
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel(
C_ID,"ex", NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager nm= getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
}
}
package com.example.earphone;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.example.earphone.App.C_ID;
public class ES extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent ni = new Intent(this,HeadsetPlugReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this,0,ni,0);
Notification notification = new NotificationCompat.Builder(this, C_ID)
.setContentTitle("Headphones plugged in")
.setContentText("currently plugged in")
.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pi).build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MainActivity extends AppCompatActivity {
Button b;
HeadsetPlugReceiver headsetPlugReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.b);
// Intent intent = new Intent(this, ES.class);
//startService(intent);
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter i = new IntentFilter();
i.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver,i);
}
}
In my app an alarm creates a notification which works but I am trying to pass a string value from my main class FoodItems.java to AlarmReceiver.java which in turn passes the String to RingtoneServiceProvider.java which creates the custom notification to be displayed. As it stands the string appears to be successfully passing into AlarmReceiver.java as I had a toast message display it before to see but when it goes to RingtoneServiceProvider.java it becomes "null".
This is part of FoodItems.java where the string value 'name' is a value entered by the user that I want to appear on the notification.
private void setAlarm(Calendar targetCal){
Toast.makeText(getApplicationContext(),
"Alarm is set for " + targetCal.getTime(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("data",name);
intent.putExtra("ID", Alarmnum);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),Alarmnum,intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
This is AlarmReceiver.java
package com.example.kev00_000.kitchenhero;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("data");
int id = intent.getIntExtra("ID", 1);
Intent service_intent=new Intent(context, RingtonePlayingService.class);
service_intent.putExtra("data",name);
service_intent.putExtra("ID", id);
context.startService(service_intent);
NotificationManager notifications = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
}
}
And here is RingtonePlayingService.java
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class RingtonePlayingService extends Service {
MediaPlayer alarm;
private String name;
private static int NOTIFICATION_ID = 1;
#Nullable
#Override
public IBinder onBind(Intent intent) {
name = intent.getStringExtra("data");
NOTIFICATION_ID = intent.getIntExtra("ID", 1);
return null;
}
public void onCreate(){
super.onCreate();
alarm=MediaPlayer.create(this, R.raw.alarmclockbuzz);
alarm.setLooping(true);
Intent stopself = new Intent(this, StopAlarm.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(this, 0, stopself, PendingIntent.FLAG_CANCEL_CURRENT);
final NotificationCompat.Builder notification
= new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setContentTitle("KitchenHero")
.setContentText("Time to put your "+name+" on!!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.addAction(R.drawable.ic_launcher, "STOP", pendingIntent);
Notification note=notification.build();
startForeground(NOTIFICATION_ID, note);
}
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.start();
return START_NOT_STICKY;
}
public void onDestroy() {
alarm.stop();
alarm.release();
}
Using Shared Preferences to do this
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
private void setAlarm(Calendar targetCal){
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("name",name);
editor.putString("ID",ID);
editor.commit();
Toast.makeText(getApplicationContext(),
"Alarm is set for " + targetCal.getTime(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),Alarmnum,intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
And get String in other class
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("name", "");
I am in the process of trying to get an email sent using BroadcastReceiver, the code is working correct using AsyncTask when using onClick but does not work when AlarmReceiver is being called.
Would it be better to use IntentService for this method? If so, what is the best way to write this?
Can anyone help with this problem? I am still new to java and want to help improve my knowledge. :)
Any help would be appreciated! Thank you!
AlarmReceiver.java
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.content.BroadcastReceiver;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import static android.graphics.Color.GREEN;
public class AlarmReceiver extends BroadcastReceiver {
Context cxt;
Activity context;
#Override
public void onReceive(Context arg0, Intent arg1) {
cxt = arg0;
addNotification();
new SendMail().execute();
}
private class SendMail extends AsyncTask<String, Integer, Void> {
protected Void doInBackground(String... params) {
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(context.getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context.getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
}
First start Intent service from Alarm manager :
private void setAlarm(Calendar targetCal){
/* HERE */ Intent intent = new Intent(getBaseContext(), AlarmService.class);
final int _id = (int) System.currentTimeMillis();
/* HERE */ PendingIntent pendingIntent = PendingIntent.getService(this,_id,intent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
......
.....
Now Intent Service class:
public class AlarmService extends IntentService {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
public AlarmService() {
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FCFCFCFC");
wakeLock.acquire();
addNotification();
sendMAIL();
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.icon_transperent)
.setLights(GREEN, 700, 700)
.setContentTitle("Achieve - Alert!")
.setContentText("This is a reminder for your deadline!");
Intent notificationIntent = new Intent(getApplicationContext(), MainMenu.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
manager.notify(0, builder.build());
}
public void sendMAIL(){
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
wakeLock.release();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Now, Manifest add:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".AlarmService" android:exported="true" android:enabled="true"/>
I'm trying to add GCM to my new application with this guide: https://developers.google.com/cloud-messaging/android/client#manifest
When I add these lines to my Manifest, It errors and do not recognize the lines
android:name="com.example.MyGcmListenerService"
android:name="com.example.MyInstanceIDListenerService"
yes, I've changed the com.example to my project details.
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service
android:name="com.example.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name="com.example.MyInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
As i read, I have to create my own Java Class for MyGcmListenerService and for MyInstanceIDListenerService, but I have no idea what to write in it?
I got really confused about all this GCM stuff.
this is what you need to write in MyGcmListenerService
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.e(TAG, "From: " + from);
Log.e(TAG, "Message: " + message);
sendNotification(message );
}
private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Sorry!!")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
this service will listen for GCM messages. and when a message will receive then onMessageReceived will trigger and then its your responsibility to handle the GCM Message. you generate any notification or what ever you want.
Step 1. Make GCM Utility Class
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class GCMUtils
{
static String TAG = "GCM";
static int NOTIFICATION_ID = 99;
public static String SENDER_ID = "YOUR SENDER ID";
Context context;
public GCMUtils(Context context)
{
this.context = context;
if (checkPlayServices())
{
Intent intent = new Intent(context, RegisterDeviceService.class);
context.startService(intent);
}
}
private boolean checkPlayServices()
{
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(context);
if (resultCode != ConnectionResult.SUCCESS)
{
return false;
}
return true;
}
}
Step 2. Make Register Device Class
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
public class RegisterDeviceService extends IntentService
{
public RegisterDeviceService() {
super(GCMUtils.TAG);
}
#Override
protected void onHandleIntent(Intent intent)
{
try
{
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(GCMUtils.SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.i(GCMUtils.TAG, "GCM Registration Token: " + token);
}
catch (Exception e)
{
Log.d(GCMUtils.TAG, "Failed to complete token refresh", e);
}
}
}
Step 3 . Make Instance ID Service
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class InstanceIdService extends InstanceIDListenerService
{
#Override
public void onTokenRefresh()
{
Intent intent = new Intent(this, RegisterDeviceService.class);
startService(intent);
}
}
Step 4. Make GCMListenerService
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gms.gcm.GcmListenerService;
public class GCMmessageListener extends GcmListenerService
{
#Override
public void onMessageReceived(String from, Bundle data)
{
String message = data.getString("price");
Log.d(GCMUtils.TAG, "From: " + from);
Log.d(GCMUtils.TAG, "Message: " + data);
sendNotification(message);
}
private void sendNotification(String message)
{
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, GCMUtils.NOTIFICATION_ID /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(message).setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(GCMUtils.NOTIFICATION_ID /* ID of notification */, notificationBuilder.build());
}
private int getNotificationIcon()
{
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.icon_lolipop : R.drawable.icon;
}
}
Step 5 Add this to your Mainefest
Add these permission
<uses-permission android:name="com.dspl.keyvendors.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
and register these Receiver and Services
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
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="YOUR PACKAGE NAME" />
</intent-filter>
</receiver>
<service
android:name=".gcm.RegisterDeviceService"
android:exported="false">
</service>
<service
android:name=".gcm.InstanceIdService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<service
android:name=".gcm.GCMmessageListener"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
Hope this will help you out...
MyGcmListenerService.java
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gms.gcm.GcmListenerService;
public class MyGcmListenerService extends GcmListenerService {
private NotificationCompat.Builder notificationBuilder;
private NotificationManager notificationManager;
private Uri defaultSoundUri;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
if (from.startsWith("/topics/")) {
String topic = from.replace("/topics/", "");
try {
if (new SharedPreferencesHelper(this).getGCMTopics().contains(topic)) {
sendNotification(message, 0);
}
} catch (NullPointerException ignored) {
}
} else {
if (message != null) {
switch (message) {
case "0":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE)
.putExtra(Constants.CLEAR_UPDATE, true));
break;
case "1":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.BOOKING_UPDATE));
sendNotification(Constants.BOOKING_NOTIFY, Integer.parseInt(message));
break;
case "2":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.PACKAGE_UPDATE));
break;
case "3":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.LOCATION_UPDATE));
break;
case "4":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.MEETING_UPDATE));
sendNotification(Constants.MEETING_NOTIFY, Integer.parseInt(message));
break;
case "5":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.MANAGER_UPDATE));
break;
case "6":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.USER_UPDATE));
break;
case "7":
startService(new Intent(this, BackgroundUpdateService.class)
.putExtra(Constants.UPDATE, Constants.WHOLE_UPDATE));
break;
default:
sendNotification(message, 0);
break;
}
}
}
}
private void sendNotification(String message, int i) {
Intent intent = new Intent(this, ActivityDrawer.class).putExtra(Constants.CLEAR_NOTIFICATION, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Context context = this;
SharedPreferencesHelper sharedPreferencesHelper = new SharedPreferencesHelper(context);
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Book That!")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentText(message)
.setContentIntent(pendingIntent);
int notificationNumber;
if (i == 1) {
notificationNumber = sharedPreferencesHelper.getBookingNotificationNumber();
sharedPreferencesHelper.setBookingNotificationNumber(++notificationNumber);
} else if (i == 4) {
notificationNumber = sharedPreferencesHelper.getMeetingNotificationNumber();
sharedPreferencesHelper.setMeetingNotificationNumber(++notificationNumber);
} else {
notificationNumber = sharedPreferencesHelper.getNotificationNumber();
sharedPreferencesHelper.setNotificationNumber(++notificationNumber);
}
notificationBuilder.setNumber(notificationNumber - 1);
notificationManager.notify(i, notificationBuilder.build());
}
}
MyInstanceIDListenerService.java
import android.content.Intent;
import com.google.android.gms.iid.InstanceIDListenerService;
public class MyInstanceIDListenerService extends InstanceIDListenerService {
#Override
public void onTokenRefresh() {
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
RegistrationIntentService.java
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import com.google.android.gms.gcm.GcmPubSub;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import java.io.IOException;
import java.util.TreeSet;
public class RegistrationIntentService extends IntentService {
Intent registrationComplete;
private SharedPreferencesHelper sharedPreferencesHelper;
public RegistrationIntentService() {
super("TokenRegistration");
}
#Override
protected void onHandleIntent(Intent intent) {
sharedPreferencesHelper = new SharedPreferencesHelper(this);
registrationComplete = new Intent(GCMConstants.REGISTRATION_COMPLETE);
InstanceID instanceID = InstanceID.getInstance(this);
try {
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
sharedPreferencesHelper.setGCMID(token);
subscribeTopics(token);
sharedPreferencesHelper.tokenStatus(true);
} catch (IOException e) {
if (e.getMessage().equals("SERVICE_NOT_AVAILABLE")) {
registrationComplete.putExtra("Error", Constants.NO_INTERNET);
}
sharedPreferencesHelper.tokenStatus(false);
}
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void subscribeTopics(String token) throws IOException {
TreeSet<String> TOPICS = new TreeSet<>();
TOPICS.add("BookThatUpdates");
sharedPreferencesHelper.setGCMTopics(TOPICS);
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}
GCMConstants.java
public class GCMConstants {
public static final String TOKEN_SAVED_IN_PREFERENCES = "tokenSavedInPreferences";
public static final String REGISTRATION_COMPLETE = "registrationComplete";
public static final String TOKEN = "Token";
public static final String TOPICS = "Topics";
}
If anything is missing please tell in comments.