I know, there are tons of these on here, but I've been trying solutions all day and haven't gotten anywhere.
Neither the example on google's docs, nor any of the 5 other ways I've found on here have worked for me at all.
As is the typical case, when I click the notification it closes the status bar and nothing new is shown onscreen.
I am creating the notification from a service and need the notification to trigger a new activity that has not yet been created.
I also will need a way to pass information to that activity via intent.
And yes... this is java for Android
What follows are the shattered remnants of my code.
package com.bobbb.hwk2;
import java.io.FileOutputStream;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.widget.Toast;
public class contactBackup extends Service
{
private NotificationManager nManager;
private static final int NOTIFY_ID = 1100;
#Override
public void onCreate()
{
super.onCreate();
String ns = Context.NOTIFICATION_SERVICE;
nManager = (NotificationManager)getSystemService(ns);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
// inform user that service has started
Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show();
String data = lookUpContacts();
if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) )
{
Context context = getApplicationContext();
// create the statusbar notification
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
//nIntent.putExtra("data",data);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
}
}
#Override
public void onDestroy()
{
nManager.cancel(NOTIFY_ID);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
// function returns string containing information
// from contacts
public String lookUpContacts()
{
...
}
public boolean saveToSDCard(String fileName, String data)
{
...
}
}
I can only hope that whatever is causing my problem is something fixable and not more of the crazy glitches I've been getting with eclipse (which no one else seems to have ever seen >:U )
If you can help me solve this problem, please share.
If you can't help with this specific problem but feel obligated to say unrelated things about posting, styles, topics, or good practice, then DON'T
Thank you :D
Edit:
You're going to have to add a flag for FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
This is because you're launching from outside your app (from the system notification bar).
This is what happens when people overwork themselves. XD
The only reason none of the tutorials I tired worked is because I misspelled my activity name in the manifest.
Thanks for stopping by
Just add following in contactBackup(service class),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN);
nIntent.setClass(context,contactViewer.class);
nIntent.putExtra("data",data);
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis());
// start notification
//PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND);
PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0);
msg.flags = Notification.FLAG_AUTO_CANCEL;
msg.setLatestEventInfo(context,
"success",
"All contacts records have been written to the file.",
pIntent);
nManager.notify(NOTIFY_ID,msg);
then get value in contactViewer class,
as,
String s=getIntent().getStringExtra("data");
Related
I didn't change anything in my app since several months but starting from 11th June I'm not able to receive any message sent by Firebase cloud messaging. It has been reported by several customers and I can confirm that it doesn't work anymore. No firmware change or anything at least on my phone. I used exactly the same code you find here. The message is sent, the callback onMessageSent in the FirebaseMessagingService is called correctly, but I'm not able to receive anything using the same account on another phone. Is there any big change I miss it? My configuration doesn't use a server so I can't check any log server side. Any tips?
The official reply I've gotten from Firebase is: they simply don't support the no-server configuration anymore.
So after 30 emails with Firebase support here's the surprise: there's nothing wrong with my code/project, and the funny thing is that they don't know why and how it worked before! Unfortunately, they didn't advise anyone about this big change, so any app based on Android device groups without a server doesn't work anymore.
Here is a possible answer to your question -
Firstly, you say that 'But I'm not able to receive anything using the same account on another phone'. Device Messaging via FCM uses the device registration token as the point of contact and not the account. Therefore, you might not receive messages from FCM with the same account on a different device.
Secondly, you can only have 20 devices registered to each token group. The Firebase Docs also mention that you usually need an app server to do device to device messaging.
Remember that this kind of device to device messaging is used only for notifications, not for sending chat messages or anything of that kind. If you want to implement notifications without an app server, try this -
import android.app.IntentService;
import android.app.NotificationChannel;
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.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.legacy.content.WakefulBroadcastReceiver;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class NotificationIntentService extends IntentService {
private static int NOTIFICATION_ID = 1;
private static final String ACTION_START = "ACTION_START";
private static final String ACTION_DELETE = "ACTION_DELETE";
public NotificationIntentService() {
super(NotificationIntentService.class.getSimpleName());
}
public static Intent createIntentStartNotificationService(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_START);
return intent;
}
public static Intent createIntentDeleteNotification(Context context) {
Intent intent = new Intent(context, NotificationIntentService.class);
intent.setAction(ACTION_DELETE);
return intent;
}
#Override
protected void onHandleIntent(Intent intent) {
Log.w(String.valueOf(new NotificationIntentService()), "onHandleIntent, started handling a notification event");
try {
String action = intent.getAction();
if (ACTION_START.equals(action)) {
processStartNotification();
}
if (ACTION_DELETE.equals(action)) {
processDeleteNotification(intent);
}
} finally {
WakefulBroadcastReceiver.completeWakefulIntent(intent);
}
}
private void processDeleteNotification(Intent intent) {
// Log something?
}
private void processStartNotification() {
// Do something. For example, fetch fresh data from backend to create a rich notification?
NOTIFICATION_ID += 1;
Intent intent = new Intent(NotificationIntentService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(NotificationIntentService.this, 0 /* Request code */, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(NotificationIntentService.this, channelId)
.setSmallIcon(R.drawable.chat)
.setContentTitle("Title")
.setContentText("Text")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(NotificationIntentService.this));
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"channel_id",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
}
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.legacy.content.WakefulBroadcastReceiver;
import java.util.Calendar;
import java.util.Date;
public class NotificationEventReceiver extends WakefulBroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL_IN_FIFTEEN_MINUTES = 0;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
600000,
alarmIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.w(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.w(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
startWakefulService(context, serviceIntent);
}
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
I'm sorry, but I won't be able to tell you much more without seeing the code.
Hope this helps.
Sources -
Firebase Docs - https://firebase.google.com/docs/cloud-messaging/concept-options#senderid
Firebase Docs - https://firebase.google.com/docs/cloud-messaging/android/device-group#managing-device-groups-on-android-client-apps
Migrate from GoogleAuthUtil and Plus.API
If you integrated with Google Sign-In in the past using GoogleAuthUtil.getToken or Plus.API, you should migrate to the newest Sign-In API for greater security and a better user experience.
Android client side
Remove the GET_ACCOUNTS (Contacts) permission if you request it
Switch any code using GoogleAuthUtil, Plus.API, AccountPicker.newChooseAccountIntent(), or AccountManager.newChooseAccountIntent() to Auth.GOOGLE_SIGN_IN_API with GoogleSignInOptions.Builder.requestIdToken(...) configuration.
https://developers.google.com/identity/sign-in/android/migration-guide
Please note that the Migrate from legacy HTTP to HTTP v1 Cautions: Any apps that use device group messaging may prefer to not upgrade. HTTP v1 does not support this feature of the FCM legacy API.
I would greatly appreciate any help with troubleshooting my use of notifications within the Android emulator. I have tried several different versions without success and the code below seems to distill the needed elements down to the minimum. The problem is that the notification simply doesn't get sent. I hear the "click" noise when I tap the button in the emulator but nothing else.
I had read somewhere that having the wrong type of image may cause problems and I have tried several. The one I have included now is generated using Vector Asset within the res folder. It feels like there is something simple that I am missing but from what I can see from all the examples I have found online the basic elements are sound.
Any help or direction would be appreciated.
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
NotificationCompat.Builder notification;
private static final int idNumber = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification = new NotificationCompat.Builder(this);
notification.setAutoCancel(true);
}
public void sendNotification(View view){
notification.setSmallIcon(R.drawable.ic_android_black_24dp);
notification.setContentText("This is the notification message");
notification.setContentTitle("Notification");
notification.setTicker("There is a notification");
notification.setWhen(System.currentTimeMillis());
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(idNumber, notification.build());
}
}
I am trying to implement Android Direct Reply notification in my app. I've managed to implement it successfully in Android N emulator. But it is not working on Marshmallow devices. When I click on action button in notification the reply edittext is not showing in devices below Android N. I know this feature will work in pre Android N devices, as it is available in WhatsApp.
My question is how to make it work in pre Android N devices? I'm sharing my code here. Any help would be great. Thanks.
MainActivity
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.RemoteInput;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
// Key for the string that's delivered in the action's intent.
public static final String KEY_TEXT_REPLY = "key_text_reply";
private static final int notificationID = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startNotif();
}
});
}
private void startNotif() {
Intent intent = new Intent(this, NotificationReciever.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
final PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
String replyLabel = "Reply";
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build();
// Create the reply action and add the remote input.
Notification.Action action =
new Notification.Action.Builder(R.drawable.ic_send,
"Action", pIntent)
.addRemoteInput(remoteInput)
.build();
// Build the notification and add the action.
Notification newMessageNotification =
new Notification.Builder(MainActivity.this)
.setSmallIcon(R.drawable.ic_remove_circle_black_48dp)
.setContentTitle("Title")
.setContentText("Content")
.addAction(action).build();
// Issue the notification.
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notificationID, newMessageNotification);
}
}
NotificationReciever
import android.app.Activity;
import android.app.RemoteInput;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
/**
* Created by User on 13-Jun-16.
*/
public class NotificationReciever extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this,getMessageText(getIntent()),Toast.LENGTH_SHORT).show();
}
private CharSequence getMessageText(Intent intent) {
Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
if (remoteInput != null) {
return remoteInput.getCharSequence(MainActivity.KEY_TEXT_REPLY);
}
Toast.makeText(this,"Remoteinput is null",Toast.LENGTH_SHORT).show();
return null;
}
}
In the docs it tells you to not use a broadcast receiver or a service for api below N. So you'd have to launch an activity which does what you want and wrap it in a pending intent instead.
if (isDirectReplySupported) {
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
}
return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Implementing this feature is very simple, first make one broadcastreceiver, as usual create a action button & hook up with pendingintent.
Then connect that intent to push notification object & notify.
In broadcastreceiver handle the reading text part & updating to notification.
Refer this post for sample example http://www.feelzdroid.com/2017/01/android-n-inline-reply-push-notifications.html
I have a service that sends a notification at a random time, telling me to press a button. This button needs to be pressed quickly because after 2 minutes it will disappear again. But after those 2 minutes I don't know how I can see if the button has or hasn't been pressed.
Somehow I need to get something like a boolean from my MainActivity to my service, but I don't believe I can do that with an intent because then I would restart my service.
I have looked for an answer but wasn't able to find a solution, any help will be much appreciated!
My service:
`package com.example.pressme_alpha;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class ButtonAlarmService extends IntentService{
private static final String INTENT_NAME = "notification";
private NotificationManager nm;
private Notification notification;
public ButtonAlarmService() {
super("Imma button!");
}
#SuppressWarnings("static-access")
#Override
protected void onHandleIntent(Intent intent) {
nm = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent newIntent = new Intent(this.getApplicationContext(), MainActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.putExtra(INTENT_NAME, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
notification = notifBuilder.setContentIntent(pendingIntent).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Press me - alpha").setContentText("You need to press the button!").build();
notifBuilder.setAutoCancel(true);
nm.notify(0, notification);
startActivity(newIntent);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check if the button is pressed here
ButtonAlarmReceiver.completeWakefulIntent(intent);
}
}
`
Extending Service (not IntentService) is what you want to do as it will keep runing untill you explicitly tell it to stop via stopService(Intent) method or if the service calls stopSelf() on its self.
You can send signals to the service via startService(Intent) method. This will start the service the first time its called (when the service is not running) and just send data to it if called subsequent times.
Make sure to spawn a new thread if you are doing heavy proccessing in the service as this will run on the Main thread (or UI thread depending on what you want to call it). You do not want to block the main thread.
Hi fellow Android coders !
I'm currently writing an application that uses the new Android 4.3 notification listener to change the notification led color when a notification is received, and am facing a problem, probably due to my lack of knowledge about how notifications work.
So far, it is working quite well. When the user switch off the screen, I create a notification, with a custom led color, and I remove it when the screen is switched ON. My problem is that when the user switch the screen back ON, he can see my notification icon on the status bar for half a second just before it is removed. Not that big of a deal, but as a nit-picker, I can't help but try a way to avoid this ugly behavior. I know that some apps succeed as doing this - LightFlow for example.
My first idea was to play with the priority of the notification and using Notification.PRIORITY_MIN nearly worked : the notification icon is not displayed on the status bar but appears when the bar is expanded.
I unfortunately discovered that notifications with minimum priority doesn't toggle the notification led when the screen is off !
I then tried to create a notification with no icon, but it is not supported by the framework - that's actually a good thing.
And now I'm out of idea.
Can someone help my find a way to create a notification that doesn't appear on the status bar but still toggles the LED on ?
Or maybe should I remove my notification before the screen is actually switched ON but I can't find a way to do this either...
If someone can help me on this one, it would make my day !
Here is the code source of my application :
Main activity :
package com.nightlycommit.coloration;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Service listener
package com.nightlycommit.coloration;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.service.notification.StatusBarNotification;
/**
* Created by Eric on 08/08/13.
*/
public class NotificationListenerService extends android.service.notification.NotificationListenerService {
private final String TAG = getClass().getSimpleName();
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenStateReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String text = "Notification posted !";
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
String text = "Notification removed !";
}
}
Screen state receiver :
package com.nightlycommit.coloration;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
/**
* Created by Eric on 12/08/13.
*/
public class ScreenStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Notification.Builder builder = new Notification.Builder(context);
builder.setLights(Color.argb(255,255,0,0), 500, 500);
builder.setContentText("TEST");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setOngoing(true);
// builder.setPriority(Notification.PRIORITY_MIN);
notificationManager.notify(777, builder.build());
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
notificationManager.cancel(777);
}
}
}
}
Thanks by advance,
Eric.