May be this is a childish question, but i am beginer please do not consider as wrong question., i was searching alot, also m following this
http://developer.android.com/guide/topics/ui/notifiers/notifications.html tutorial. and also google to solve my problem but i could't find.
This is my assignment.
I have a EditText and a Button in main activity, When i click the button a notification is generated, when i am opening that notification another activity is open, shows Editext data, which i have entered in the main activity through EditText.
my Question is....
I want to Show the count of pending notifications in a single Notification window as in http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Updating
but i could't understand this --> Start of a loop that processes data and then notifies the user....
how can i achive this. how can i process data to get the pending count. keep in mind this count will decrement when there is no notification???
When click a notification than i want to get all notifications in a separate activity just like a messages in inbox.
e.g. in my main activity i am clicking the button 10 times, so actually 10 notifications will generate in a single notification window with count=10, but it shows count = 1?? when i open the notifications than it will only show the latest notification contents in another activity, how can i show remaining 9 in a single activity??
Below in my Main activity....
Button btn;
EditText edtText;
NotificationCompat.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
edtText = (EditText) findViewById(R.id.editText);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CreteNotification(Calendar.getInstance().getTimeInMillis(), edtText.getText().toString());
}
});
}
protected void CreteNotification(long when, String data) {
String notificationContent ="Notification Content Click Here to go more details";
String notificationTitle ="This is Notification";
int number = 1;
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
int smalIcon =R.drawable.ic_launcher;
String notificationData = data;
Intent intent = new Intent(getApplicationContext(), MyNotificationClass.class);
intent.putExtra("Message", notificationData);
intent.putExtra("Time", Integer.toString((int) when) );
intent.setData(Uri.parse("content://"+when));
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager =(NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_VIBRATE| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
// Start of a loop that processes data and then notifies the user
// how to loop??????????????????
notificationBuilder.setNumber(++number);
Notification notification = notificationBuilder.getNotification();
notificationManager.notify(1, notification);
}
code where i want to show all notifications?????
HashMap<String, String> inboxMsg;
TextView notiTextView;
Button btn;
int Id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_notification_class);
inboxMsg = new HashMap<String, String>();
Id = 0;
notiTextView = (TextView) findViewById(R.id.textView1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#SuppressWarnings("rawtypes")
#Override
public void onClick(View v) {
Set<String> keys = inboxMsg.keySet();
Iterator keyItra = keys.iterator();
while (keyItra.hasNext()) {
String k = (String) keyItra.next();
String Message = inboxMsg.get(k);
notiTextView.setText(Message);
}
}
});
if(savedInstanceState == null)
{
String Mesage = getIntent().getExtras().getString("Message");
String Time = getIntent().getExtras().getString("Time");
inboxMsg.put(Integer.toString(++Id), "Message is " + Mesage + " Time " + Time + "\n");
}
}
where is the problem kindly redirect me to the correct path, also kindly guide me how to achive this.
The reason why you are not getting the actual notification count is that whenever CreteNotification(long when, String data) method is called number variable is set to 1. It can be solved by instead of declaring it inside a method make number a class member variable.
Button btn;
EditText edtText;
NotificationCompat.Builder builder;
int number = 1;
.....
protected void CreteNotification(long when, String data) {
.....
notificationBuilder.setNumber(++number);
....
}
Regarding starting different activity for every notification, you need to pass different 'ID' for each notification when calling notificationManager.notify(ID, notification); method, but remember if you assign different ID, triggering new notification won't update the count but add a new notification. So clicking the button for generating notification will actually generate 10 different notifications.
Related
Recently, I have been meticulously looking over these two questions and solutions to the issue of trying to have multiple notifications that each have their own activities that grab String extras from their own corresponding notification.
How to pass text from notification to another activity?
How to send parameters from a notification-click to an activity?
For the most part the current solution works except for one key issue:
When the application is not open, and I receive two different notifications. I click to open the notification detail activity and the text in the activity updates just fine. However, while keeping the same activity up, I click on the second notification and nothing happens.
When the application is open, this solution works fine. It opens two separate intents with two different notification text views. If the application is closed, and I exit out of the first notifications view details activity and then open up the second, it also accomplishes the solution fine.
Any help would be greatly appreciated!
Here is my code:
MainActivity class
private NotificationManager notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void setAlarm1(View view){
Toast.makeText(getApplicationContext(),"Setting Alarm 5 seconds",Toast.LENGTH_SHORT).show();
//this is 5 seconds
long alertTime = new GregorianCalendar().getTimeInMillis();
alertTime += 5*1000;
Intent alertIntent = new Intent(this,AlertReceiver.class);
alertIntent.putExtra("msg","This is msg for 5 seconds");
alertIntent.putExtra("msgText","This is msgText for 5 seconds");
alertIntent.putExtra("msgAlert","This is msgAlert for 5 seconds");
alertIntent.putExtra("notifyID",1);
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime,
PendingIntent.getBroadcast(this,1,alertIntent,
0));
}
public void setAlarm2(View view){
Toast.makeText(getApplicationContext(),"Setting Alarm 10 seconds",Toast.LENGTH_SHORT).show();
//this is 5 seconds
long alertTime = new GregorianCalendar().getTimeInMillis();
alertTime += 10*1000;
Intent alertIntent = new Intent(this,AlertReceiver.class);
alertIntent.putExtra("msg","This is msg for 10 seconds");
alertIntent.putExtra("msgText","This is msgText for 10 seconds");
alertIntent.putExtra("msgAlert","This is msgAlert for 10 seconds");
alertIntent.putExtra("notifyID",2);
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime,
PendingIntent.getBroadcast(this,2,alertIntent,
0));
}
AlertReceiver class
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context, intent.getStringExtra("msg"), intent.getStringExtra("msgText"), intent.getStringExtra("msgAlert"), intent.getIntExtra("notifyID",999));
}
public void createNotification(Context context, String msg, String msgText, String msgAlert, int notifyID){
Intent intent = new Intent(context, MoreInfoNotification.class);
intent.putExtra("msg",msg);
intent.putExtra("msgText",msgText);
intent.putExtra("msgAlert",msgAlert);
// had this below line of code but made problems worse
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent notificIntent = PendingIntent.getActivity(context, notifyID,
intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
style.setBigContentTitle(msg);
style.bigText(msgText);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(msg);
builder.setContentText(msgText);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setTicker(msgAlert);
builder.setStyle(style);
builder.setContentIntent(notificIntent);
builder.setDefaults(NotificationCompat.DEFAULT_SOUND);
builder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(notifyID,builder.build());
}
}
MoreInfoNotification class
public class MoreInfoNotification extends AppCompatActivity {
private TextView mTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent) {
// TODO Auto-generated method stub
Bundle extras = getIntent().getExtras();
if(extras != null){
setContentView(R.layout.activity_more_info_notification);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView)findViewById(R.id.textView);
String totalString = "";
if(extras.containsKey("msg")){
totalString += extras.getString("msg");
}
if(extras.containsKey("msgText")){
totalString += ", " + extras.getString("msgText");
}
if(extras.containsKey("msgAlert")){
totalString += ", " + extras.getString("msgAlert");
}
mTextView.setText(totalString);
}
}
}
So I recently found the answer to this problem. The Intents were seen as the same instead of separate, which is what I was looking for. In order to get the Intents away from being viewed as duplicates I wrote this line:
intent.setAction("com.wordpress.zackleaman.materialtablayout.intent.action.ACTION_NAME" + notifyID);
In my AlertReceiver class, createNotification method, right after I put the extras in my intent.
I know that the best method is to use:
PendingIntent.getActivity(context, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
with: intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
However no matter how many different solutions I tried, I could not get the text to update if I had the first notification detail open and I clicked to open the second notification detail while the application was originally closed.
When creating a recommendation (or Notification) in Lollipop on Android TV, I cannot get it to Auto-cancel.
I am using the "NotificationCompat.BigPictureStyle" as recommended in the Android TV developer pages. The notification works as designed, triggering the PendingIntent as expected but does not auto-cancel and dissappear from recommendations bar. A second selection of the recommendation brings up a blank screen, so I guess the PendingIntent is null at that point. (ADB shows android.content.IntentSender$SendIntentException on 2nd invocation.)
Tested on Nexus Player and Android TV Emulator.
private void buildAndroidTVRecommendation(String name, PendingIntent pIntent,
Context context2, Bundle extras) {
NotificationManager mNotificationManager = (NotificationManager)
context2.getSystemService(Context.NOTIFICATION_SERVICE);
Bitmap smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.air_share);
Notification notification = new NotificationCompat.BigPictureStyle(
( new NotificationCompat.Builder(context)
.setContentTitle("Air-Share - incoming share")
.setContentText("From: "+name)
.setContentInfo("Air-Share"))
.setGroup("Air-Share")
.setColor(0xFFFF2020)
.setCategory(Notification.CATEGORY_RECOMMENDATION)
.setLargeIcon(smallBitmap)
.setSmallIcon(R.drawable.air_share)
.setContentIntent(pIntent)
.setExtras(extras)
.setAutoCancel(true)
)
.build();
mNotificationManager.notify(pendingCounter, notification);
mNotificationManager = null;
}
For what it's worth I have created a work-around to get by this issue.
I created a new Activity whose sole purpose is to receive a Pending intent from the Recommendation.
I alter the original Pending Intent of the recommendation to invoke this new activity instead of my desired activity. (The desired activity is outside my app.) In the Extras, I bundle everything I need to know for my original desired intent as well as the notification ID.
When the new activity is launched (after user clicks on recommendation), I extract the ID and cancel the recommendation. I then extract the information for the desired intent, create the intent and finally finish the activity.
public class TVRecommendationActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = (Intent) getIntent();
String jsonString = in.getStringExtra("jsonString");
String fileUri = in.getStringExtra("fileUri");
int id =in.getIntExtra("notificationID", -1);
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (id >= 0 ) nm.cancel(id);
JSONIntent newIntent = new JSONIntent(getApplicationContext());
newIntent.setIncomingLocalFileURI(fileUri);
Intent out = newIntent.buildIntentFromJSON(jsonString, fileUri);
if (out != null) startActivity(out);
finish();
}
}
I have followed tutorial in http://developer.android.com/training/notify-user/index.html
It works well. But what I want is : when I click ping, the old service will we stopped, and then create the service again. So if I clicked id multiple time, It will notify me only once.
Problem: If I set time 10, then I click "Ping" button. Then after 5 second, I click it again. It will notify me twice.
What I want : If I set time 10, then I click "Ping" button. Then after 5 second, I click it it will notify only once, 10 secondds after the last time I click the button.
public class MainActivity extends Activity {
private Intent mServiceIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creates an explicit Intent to start the service that constructs and
// issues the notification.
mServiceIntent = new Intent(getApplicationContext(), PingService.class);
}
/*
* Gets the values the user entered and adds them to the intent that will be
* used to launch the IntentService that runs the timer and issues the
* notification.
*/
public void onPingClick(View v) {
stopCurrentService();
int seconds;
// Gets the reminder text the user entered.
EditText msgText = (EditText) findViewById(R.id.edit_reminder);
String message = msgText.getText().toString();
mServiceIntent.putExtra(CommonConstants.EXTRA_MESSAGE, message);
mServiceIntent.setAction(CommonConstants.ACTION_PING);
Toast.makeText(this, R.string.timer_start, Toast.LENGTH_SHORT).show();
// The number of seconds the timer should run.
EditText editText = (EditText) findViewById(R.id.edit_seconds);
String input = editText.getText().toString();
if (input == null || input.trim().equals("")) {
// If user didn't enter a value, sets to default.
seconds = R.string.seconds_default;
} else {
seconds = Integer.parseInt(input);
}
int milliseconds = (seconds * 1000);
mServiceIntent.putExtra(CommonConstants.EXTRA_TIMER, milliseconds);
// Launches IntentService "PingService" to set timer.
startService(mServiceIntent);
}
private void stopCurrentService() {
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
if (serviceList.size() <= 0) { }
int size = serviceList.size();
for (int i = 0; i < size; i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName serviceName = serviceInfo.service;
if (serviceName.getClassName().equals(PingService.class.getName())) {
try {
Intent intentstop = new Intent();
intentstop.setComponent(serviceName);
getApplicationContext().stopService(intentstop);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
}
PingService creates a notification that includes 2 buttons: one to snooze the
notification, and one to dismiss it.
public class PingService extends IntentService {
private NotificationManager mNotificationManager;
private String mMessage;
private int mMillis;
NotificationCompat.Builder builder;
private boolean status;
public PingService() {
// The super call is required. The background thread that IntentService
// starts is labeled with the string argument you pass.
super("com.example.android.pingme");
}
#Override
protected void onHandleIntent(Intent intent) {
// The reminder message the user set.
mMessage = intent.getStringExtra(CommonConstants.EXTRA_MESSAGE);
// The timer duration the user set. The default is 10 seconds.
mMillis = intent.getIntExtra(CommonConstants.EXTRA_TIMER,
CommonConstants.DEFAULT_TIMER_DURATION);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String action = intent.getAction();
// This section handles the 3 possible actions:
// ping, snooze, and dismiss.
if (action.equals(CommonConstants.ACTION_PING)) {
issueNotification(intent, mMessage);
} else if (action.equals(CommonConstants.ACTION_SNOOZE)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.snoozing));
// Sets a snooze-specific "done snoozing" message.
issueNotification(intent, getString(R.string.done_snoozing));
} else if (action.equals(CommonConstants.ACTION_DISMISS)) {
nm.cancel(CommonConstants.NOTIFICATION_ID);
}
}
private void issueNotification(Intent intent, String msg) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Sets up the Snooze and Dismiss action buttons that will appear in the
// expanded view of the notification.
Intent dismissIntent = new Intent(this, PingService.class);
dismissIntent.setAction(CommonConstants.ACTION_DISMISS);
PendingIntent piDismiss = PendingIntent.getService(this, 0,
dismissIntent, 0);
Intent snoozeIntent = new Intent(this, PingService.class);
snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);
PendingIntent piSnooze = PendingIntent.getService(this, 0,
snoozeIntent, 0);
// Constructs the Builder object.
builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification)
.setTicker("Ping ! ping ! PIng!")
.setContentTitle(getString(R.string.notification))
.setContentText(getString(R.string.ping))
.setDefaults(Notification.DEFAULT_ALL)
// requires VIBRATE permission
/*
* Sets the big view "big text" style and supplies the text (the
* user's reminder message) that will be displayed in the detail
* area of the expanded notification. These calls are ignored by
* the support library for pre-4.1 devices.
*/
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.addAction(R.drawable.ic_stat_dismiss,
getString(R.string.dismiss), piDismiss)
.addAction(R.drawable.ic_stat_snooze,
getString(R.string.snooze), piSnooze);
/*
* Clicking the notification itself displays ResultActivity, which
* provides UI for snoozing or dismissing the notification. This is
* available through either the normal view or big view.
*/
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Because clicking the notification opens a new ("special") activity,
// there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
startTimer(mMillis);
}
// Starts the timer according to the number of seconds the user specified.
private void startTimer(int millis) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_start));
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.sleep_error));
}
Log.d(CommonConstants.DEBUG_TAG, getString(R.string.timer_finished));
issueNotification(builder);
}
private void issueNotification(NotificationCompat.Builder builder) {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Including the notification ID allows you to update the notification
// later on.
mNotificationManager.notify(CommonConstants.NOTIFICATION_ID,
builder.build());
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I have called stopService(), but the old notification shows up again.
What I want is it will notify me once, 10 seconds after the latest click.
You can use handler in order to stop/start your service.
Please look at my code. It's not exactly related to your code but you can get the idea.
Click this link
You can do checking in Run method of Runnable.
When the custom notification is peeking on the homescreen, the system displays it with a standard template that it generates from the notification's semantic data. I have to swipe the notification up, to see the custom activity for the notification. I'm showing 'Swipe up to view' text as title for standard template. My question is, Can i replace "Swipe up to view" with a time counter, which increase with timer?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String ns = getApplicationContext().NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) getSystemService(ns);
callNotification(Html.fromHtml(getFormattedTime(CurrentPausedTime)),false,false);
Thread notifyingThread = new Thread(null, updateTimerTaskCustom, "NotifyingServiceNew");
notifyingThread.start();
}
private void callNotification(final Spanned spanned,boolean isPause,boolean pauseAction) {
// TODO Auto-generated method stub
displayIntent = new Intent(getApplicationContext(), CustomNotification.class);
displayIntent.putExtra("exerciseTitle", "Running");
displayIntent.putExtra("duration", CurrentPausedTime);
displayIntent.putExtra("elepsedTime", 0);
displayIntent.putExtra("isPause", isPause);
displayPendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent deleteIntent = new Intent(getApplicationContext(), ClearNotification.class);
deletePendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent pauseIntent = new Intent(ExerciseActionReciever.ACTION_PAUSE,
null,getApplicationContext(), ExerciseActionReciever.class);
pausePendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent stopIntent =new Intent(ExerciseActionReciever.ACTION_STOP,
null,getApplicationContext(), ExerciseActionReciever.class);
stopPendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent resumeIntent = new Intent(ExerciseActionReciever.ACTION_RESUME,
null, getApplicationContext(), ExerciseActionReciever.class);
resumePendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, resumeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.WearableExtender wearableExtender =
new NotificationCompat.WearableExtender()
.setHintHideIcon(true)
.setContentIcon(R.drawable.icon)
.setDisplayIntent(displayPendingIntent);
mNotifyBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.icon)
.setContentTitle(""+spanned)
.setDeleteIntent(deletePendingIntent)
.extend(wearableExtender)
.addAction(R.drawable.icon, "Resume", resumePendingIntent)
.addAction(R.drawable.icon, "Stop", stopPendingIntent);
}
private Runnable updateTimerTaskCustom = new Runnable() {
public void run() {
timerHandlerCustom.removeCallbacks(updateTimerTaskCustom);
timerHandlerCustom.postDelayed(updateTimerTaskCustom, 1000);
if(!CustomNotification.isCustomCardAcrivityvisible )
{
CurrentPausedTime = CurrentPausedTime+1000;
mNotifyBuilder.setContentTitle(""+Html.fromHtml(getFormattedTime(CurrentPausedTime)));
mNotificationManager.notify(NOTIFICTIONTION_ID , mNotifyBuilder.build());
}
}
};
You can replace "Swipe up to view" with any text you want - like "53 sec". To update this value you will need to simply update your notification.
More information about updating notifications: http://developer.android.com/training/notify-user/managing.html
BTW. If you want to optimise your code the note on top might be important to you:
When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
Instead, you should consider updating a previous notification, either
by changing some of its values or by adding to it, or both.
EDIT: If you want, in addition, to use this solution with custom layout Activity you need to prevent notification from refreshing when this Activity is visible. Otherwise you will end up with Activity being created over and over again (blinking layout). Custom Activity in card layout is visible between the onResume and onPause events, so you need to detect that and update the whole notification ONLY when Activity is NOT visible to the user. The simpliest way is to use a static flag, but you can also play with other more advanced solutions (like LocalBroadcastManager etc.) to achieve this goal.
public class CustomLayoutActivity extends Activity {
public static boolean isCustomCardAcrivityvisible;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_layout_activity);
}
#Override
protected void onResume() {
super.onResume();
isCustomCardAcrivityvisible = true;
}
#Override
protected void onPause() {
super.onPause();
isCustomCardAcrivityvisible = false;
}
}
and if you're about to refresh your notification just do following check:
if(!CustomLayoutActivity.isCustomCardAcrivityvisible) {
updateNotification();
}
Alternatively you can use setUsesChronometer(boolean b) method, to just display a timer (instead of contextText) that will be refreshed for you, but please notice that the timer will only be displayed (on Android Wear) if you will NOT set a custom layout to your card. So while this is not exactly what you want, you may consider this instead.
Show the when field as a stopwatch. Instead of presenting when as a
timestamp, the notification will show an automatically updating
display of the minutes and seconds since when. Useful when showing an
elapsed time (like an ongoing phone call).
I'm coding an android app for my school, and i have a little problem with notifications:
My app checks if the homepage was updated (date of page is newer than date of last view) in background. If the page was updated, the app builds a notifications (till here it works fine) with 2 options: Dismiss or show (also works). "Show" works fine, but my problem is "Dismiss" because it has to update the date in settings and it should quit then, but it's always showing the last opened activity.
I'm having an Activity which manages this with Intent extras:
public class ***********Handler extends Activity {
String EXTRA_ACTION = "de.xorg.*****.ACTION";
String EXTRA_VPDATE = "de.xorg.*****.VPDATE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ntd);
Intent intent = getIntent();
String todo = intent.getStringExtra(EXTRA_ACTION); //Action from Notification ("D" or "S")
String date = intent.getStringExtra(EXTRA_VPDATE); //New date
if(todo.toLowerCase().contains("d")) {
//update date value
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("readDate", date);
editor.commit();
// Remove notification
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
// Quit app (1st method) [I'm only using one in real code, but both aren't working]
android.os.Process.killProcess(android.os.Process.myPid());
// Quit app (2nd method)
finish();
} else {
//update date value
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("readDate", date);
editor.commit();
// Remove notification
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
//Set theme (not important now)
Boolean BeanUI = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("bean", false);
String URL;
if(BeanUI) {
URL = "*****" + PreferenceManager.getDefaultSharedPreferences(this).getString("klasse", "") + "&fc=ffffff&bc=000000";
} else {
URL = "*****" + PreferenceManager.getDefaultSharedPreferences(this).getString("klasse", "");
}
String EXTRA_URL = "de.xorg.*****.MESSAGE";
String EXTRA_NAME = "de.xorg.*****.MESSAGENAME";
Intent intent2 = new Intent(this, InternetViewer.class);
intent2.putExtra(EXTRA_URL, URL);
intent2.putExtra(EXTRA_NAME, ",Vertretungsplan");
startActivity(intent2);
}
}
}
And here's the code which creates the notification:
// I've censored all private values with ***'s
// CheckService.MC = Context of main activity
// CheckService.NM = NotificationManager
public static void PostNotification(String text, String datum) {
Intent intentS = new Intent(CheckService.MC, ***************Handler.class);
Intent intentD = new Intent(CheckService.MC, ***************Handler.class);
String EXTRA_ACTION = "de.xorg.*****.ACTION";
String EXTRA_DATE = "de.xorg.*****.VPDATE";
intentS.putExtra(EXTRA_ACTION, "S");
intentS.putExtra(EXTRA_DATE, datum);
intentD.putExtra(EXTRA_ACTION, "D");
intentD.putExtra(EXTRA_DATE, datum);
PendingIntent pIntentD = PendingIntent.getActivity(CheckService.MC, 0, intentD, 0);
PendingIntent pIntentS = PendingIntent.getActivity(CheckService.MC, 0, intentS, 0);
// Build notification
Notification n = new Notification.Builder(CheckService.MC)
.setContentTitle("Title")
.setContentText(text)
.setSmallIcon(R.drawable.vertretung)
.setContentIntent(pIntentS)
.setAutoCancel(true)
.addAction(R.drawable.anzeigen, "Show", pIntentS)
.addAction(R.drawable.gelesen, "Dismiss", pIntentD).build();
CheckService.NM.notify(0, n);
}
I've tried to do it with »finish();« and with »android.os.Process.killProcess(android.os.Process.myPid());« both aren't working.
Why doesn't that work? Is there a different (better) way to update the setting?