im trying to launch application form notification using Android Edk. I succeded to display notification. But i want to launch my application from notification and i can`t make it work.
Notification is received when application is not running, is triggered from a broadCast reciever.
I think my problem is related to the activity that i created from notification intent.
Here the notification function:
Intent resultIntent = new Intent(context, TaskManagerActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent = PendingIntent.getActivity( context, 0, resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context )
.setSmallIcon(R.drawable.ic_menu_day)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(resultPendingIntent)
.setWhen(System.currentTimeMillis());
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
And here is my activity class:
public class TaskManagerActivity extends Activity
{
public static TaskManagerActivity m_Activity;
private static final String TAG = "TaskManagerActivity";
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
}
}
Have a look at official docs of Android about notification. Also I'd suggest you to read this post of SO.
Related
I need help how to send push notifications on successful payment with transaction I'd to user
Use one of the background workers if you want to check the status of your transaction in background. I will use WorkManager.
implementation "android.arch.work:work-runtime:1.0.1"
public class SynchronizeWorker extends Worker {
static final String TAG = "MYWORKER";
public SynchronizeWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
private Notification getNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"WTF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("WTF_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
// specify the class of the activity you want to open after click on notification
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
intent,
0);
return new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getApplicationContext().getResources().getString(R.string.notification_header))
.setContentText(getApplicationContext().getResources().getString(R.string.notification_text))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.build();
}
#NonNull
#Override
public Result doWork() {
Log.d(TAG, "status checking started");
// check your transaction status here and show notification
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Log.d(TAG, "status checking finished");
}
Log.d(TAG, "status checking finished");
NotificationManagerCompat
.from(getApplicationContext())
.notify((int)(Math.random() * 10), getNotification());
return Result.success();
}
}
And then enqueue worker where you want to check status
OneTimeWorkRequest myWorkRequest = new OneTimeWorkRequest.Builder(SynchronizeWorker.class).build();
WorkManager.getInstance().enqueue(myWorkRequest);
I understand that it is probably not exactly what you want, but hope it will help somehow:)
QuickBlox not delivering GCM notifications to subscribed devices. I tried sending notification message from Admin Panel too, but it isn't delivered to device, but still in Admin Panel it shows it as "sent". But no history available.
And also what could be the reason for this ? How to mitigate this ?
How to view sent GCM notifications.
The admin panel is not good enough - it lies sometime by saying 'send successfully' but it never reaches the other end.
Try sending the GCM notification by using the code snippet provided in the documentation. It works always.
public void sendMessageOnClick() {
// Send Push: create QuickBlox Push Notification Event
QBEvent qbEvent = new QBEvent();
qbEvent.setNotificationType(QBNotificationType.PUSH);
qbEvent.setEnvironment(QBEnvironment.DEVELOPMENT);
// generic push - will be delivered to all platforms (Android, iOS, WP, Blackberry..)
qbEvent.setMessage("how are you doing");
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6132691);
qbEvent.setUserIds(userIds);
QBMessages.createEvent(qbEvent, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
}
#Override
public void onError(List<String> strings) {
// errors
}
});
}
//OR the below:--
private void sendPushNotifications(){
// recipients
StringifyArrayList<Integer> userIds = new StringifyArrayList<Integer>();
userIds.add(6114793);
//userIds.add(960);
QBEvent event = new QBEvent();
event.setUserIds(userIds);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, String> data = new HashMap<String, String>();
data.put("data.message", "Hello");
data.put("data.type", "welcome message");
event.setMessage(data);
QBMessages.createEvent(event, new QBEntityCallbackImpl<QBEvent>() {
#Override
public void onSuccess(QBEvent qbEvent, Bundle args) {
// sent
}
#Override
public void onError(List<String> errors) {
}
});
}
I am writing an app which has GCM in it. I am not trying to compete with Whatsapp. It should just a sort of bulletin board between all those who use this app.
The app is opened with a menu of buttons and one of them directs the user to the Messages activity.
As long as you stay on this activity, the messages are there and everything works as it should be.
But, if I go back to the menu activity and then go back into the messages activity, then all messages are gone and are not shown.
I am using ListActivity for the messages and the onCreate function, destroys the current list each time it is read.
My question is, how can I return to the messages activity without loosing them? I want to have it as in Whatsapp, when you go into Whatsapp the messages are always there!
I thought of saving the messages list into a file and then read it (or let's say the last 40-50 messages) anytime the onCreate is called. Is this a good solution? Is there any solution without saving the list to a file?
Here is some of my code inside the messages activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_main);
Intent in = getIntent();
username = in.getStringExtra("username");
password = in.getStringExtra("password");
nickname = in.getStringExtra("nickname");
messages = new ArrayList<Message>();
txtNewMsg = (EditText) this.findViewById(R.id.text);
adapter = new MessagesAdapter(this, messages);
setListAdapter(adapter);
registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
Spanned newMessageDate = Html.fromHtml("<small><i><font color=\"red\">" + currentDateandTime + "</font></i></small>" + " " + "<small><i><font color=\"blue\">" + nickname + "</font></i></small>" + "<br />" + newMessage);
addNewMessage(new Message(newMessageDate, true));
WakeLocker.release();
}
};
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
void addNewMessage(Message m)
{
messages.add(m);
adapter.notifyDataSetChanged();
getListView().setSelection(messages.size()-1);
}
The code includes: onCreate, BroadcastReceiver (GCM receiver), onDestroy and addNewMessage which adds the new message to the messages list.
Thanks for any help!
AJ
Create database with message table and users table which will store the message and users details.
Now whenever new message is come store in database and then when you open the app load limited message from table. If the app is open and message is come first store in your database and add to your list object and invalidate your listview.
It's possible to have Alarm Manager with Broadcast Receiver in One class without Activity like this:
public class AlarmReceiver extends BroadcastReceiver {
private static final int MY_NOTIFICATION_ID=1;
NotificationManager notificationManager;
Notification myNotification;
private final String myBlog = "http://android-er.blogspot.com/";
#Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 11);
calendar.set(Calendar.MINUTE, 43);
calendar.set(Calendar.SECOND, 0);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 1,
intent1, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent1);
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification = new NotificationCompat.Builder(context)
.setContentTitle("Exercise of Notification!")
.setContentText("http://android-er.blogspot.com/")
.setTicker("Notification!").setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher).build();
notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
}
}
and I would like to this Alarm Manager work without app on.
without app on , without Activity and without Service. No you can't. you need a context in which you will define your broadcast receiver. you can use the context of an activity or a service or the application.
You can creat the class like this , but then you should instantiate it somewhere in an activity ...
This works: IntentService with NotificationCompat.Builder providing a notification to use with NotificationManager.notify() .setContentIntent(pendingIntent) is needed. When notify is sent, the notification appears in the notification AND IS PERSISTENT (stays alive until the user clicks it, at which point it starts the activity specified in .setContentIntent). Good!
What does not work: I would like the service to be long-lived like a phone-service, so startForeground() would seem advised. However, when I include that, the associated notification does indeed appear in the tray as it should, but it is NOT PERSISTENT and disappears when the IntentService ends (unlike above). (The associated notification also uses .setContentIntent and starts another Activity.)
Any thoughts? It is critical that the service not die until it detects a certain (rare) "event". It is also critical that the notification remains alive until the user responds by clicking it!
Here is the boiled-down code (latter case): Thanks!
public class SService extends IntentService {
public SService() {
super("SService");
}
#Override
protected void onHandleIntent(Intent sIntent) {
//Notification construction:
Notification notif;
Context context = this;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent bIntent = new Intent(context, BarNotifActivity.class);
PendingIntent pbIntent = PendingIntent.getActivity(context, 0, bIntent,0);
Notification barNotif;
NotificationCompat.Builder bBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.bar_title))
.setContentText(getString(R.string.bar_text))
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pbIntent);
barNotif = bBuilder.build();
this.startForeground(1, barNotif);
long[] vibration = {0, 300, 1000, 300, 1000, 300, 1000, 300, 1000};
Intent mIntent = new Intent(context, NotifReceiverActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, mIntent,0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.alert_text))
.setContentText(getString(R.string.alert_text))
.setTicker("**Notification Arrived!**")
.setVibrate(vibration)
//.setAutoCancel(true)
.setOngoing(true)
.setContentIntent(pIntent);
notif = mBuilder.build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_INSISTENT;
try {
Thread.sleep(7000); //Pause 7 sec.
} catch (InterruptedException e) {
e.printStackTrace();
}
mNotificationManager.notify(1, notif);
}
}