Notification Send Text to Activity Issue - android

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.

Related

Listen chrome custom tab progress event

I have an application using Chrome custom tabs to open some links, I need to have event each second during all the time the user stay on Chrome, or know how many time he stay on Chrome. For me the only way to do it is to use a Service. Is it possible to do it differently?
Create your YourBroadCastReceiver class as follows
public class YourBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Called every 60 seconds","called");
}
}
After starting your custom tab successfully create Alarm PendingIntent that will trigger YourBroadCastReceiver once every 60 sec.
// Retrieve a PendingIntent that will perform a broadcast
Intent repeatingIntent = new Intent(context,
YourBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Set the alarm to start at 10:00 AM
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
manager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60 * 1000, // repeat for every 60 seconds
pendingIntent);
after closing your custom tab never forget to cancel your PendingIntent
PendingIntent.getBroadcast(
context, _pendingIntentId, alarmIntent, 0).cancel();
For implementation of chrome custom tabs I've followed this tutorial, github link.
My solution basically rely on boolean and System.currentTimeMillis().
Step - 1 : Declare two class global variables,
private boolean isCustomTabsLaunched = false;
private long customTabsEnterTime;
Step - 2 : Set values for above to variables when launchUrl.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "FloatingActionButton");
// Launch Chrome Custom Tabs on click
customTabsIntent.launchUrl(CustomTabsActivity.this, Uri.parse(URL));
isCustomTabsLaunched = true;
customTabsEnterTime = System.currentTimeMillis();
Log.d(TAG, "customTabsEnterTime = " + customTabsEnterTime);
}
});
Step - 3 : Calculate stay time in onResume method.
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
if (isCustomTabsLaunched) {
isCustomTabsLaunched = false;
calculateStayTime();
}
}
private void calculateStayTime() {
long customTabsExitTime = System.currentTimeMillis();
Log.d(TAG, "customTabsExitTime = " + customTabsExitTime);
long stayTime = (customTabsExitTime - customTabsEnterTime) / 1000; //convert in seconds
Log.d(TAG, "stayTime = " + stayTime);
}
In order to make code more robust you may like to store boolean isCustomTabsLaunched and long customTabsEnterTime in preferences or database so in any case these two params get destroyed as your activity may get destroy in background if user stay for long time in chrome custom tab.

I am trying to create an Alarm on my Android Studio 1.4

Trying to create a simple Alarm. Reading through the article of Android Dev here
http://developer.android.com/reference/android/provider/AlarmClock.html
I get an idea that the Alarm should go off even when the application is not running and the phone is on sleep mode. I tried all the tutorials available on YT and all the answers I could search for online but using any of these examples I just couldn't make my alarms go off when my phone is asleep. I tried adding wake up permission on the manifest and used wakefulbroadcastreceier insted of simple broadcast receiver but it doesn't help. The alarm goes off only when the app is running in the background. Here is my alarm function
public void _setAlarm()
{
Long alerttime = new GregorianCalendar().getTimeInMillis()+60*1000;
Intent _alarmIntent = new Intent(this, Alert.class);
ArrayList<String> _displayItem = _displayItem();
_alarmIntent.putStringArrayListExtra("Text1", _displayItem);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alerttime, PendingIntent.getBroadcast(this,1,
_alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}
And here is the Alert class
public class Alert extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//PendingIntent _alarmIntent = PendingIntent.getActivity(context,0, new Intent(context,Alarm.class),0);
Intent _alarmIntent = new Intent (context, Alarm.class);
ArrayList<String> data = intent.getStringArrayListExtra("Text1");
_alarmIntent.putStringArrayListExtra("Text1",data);
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder _alarmBuilder = new NotificationCompat.Builder(context)
.setContentTitle("Get up")
.setContentText("Get Up")
//.setSound(uri)
.setTicker("SonsofGun")
.setSmallIcon(R.drawable.edit_icon);
TaskStackBuilder tStackBuilder = TaskStackBuilder.create(context);
tStackBuilder.addParentStack(Alarm.class);
tStackBuilder.addNextIntent(_alarmIntent);
PendingIntent _alarmPIntent = tStackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
_alarmBuilder.setContentIntent(_alarmPIntent);
_alarmBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
//_alarmBuilder.setAutoCancel(true);
NotificationManager _alarmManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
_alarmManager.notify(1, _alarmBuilder.build());
}
And the following is my alarm activity with custom expandable list
public class Alarm extends AppCompatActivity {
TextView _item, _title;
HashMap<String,List<String>> _itemDisplay;
List<String> _list;
ExpandableListView _expLV;
expLVAdapter _expAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
//Adding font to notification title---------------------------------------------------------
_title = (TextView) findViewById(R.id.textViewNotificationTitle);
Typeface amaticTF = Typeface.createFromAsset(getAssets(), "Amatic-Bold.ttf");
_title.setTypeface(amaticTF);
// End of notification title----------------------------------------------------------------
_expLV = (ExpandableListView) findViewById(R.id.expListView);
ArrayList<String> _displayItem = getIntent().getStringArrayListExtra("Text1");
_itemDisplay = getInfo(_displayItem);
_list = new ArrayList<String>(_itemDisplay.keySet());
_expAdapter = new expLVAdapter(this,_itemDisplay,_list);
_expLV.setAdapter(_expAdapter);
}
//Adding values to the expandable list view
public static HashMap<String,List<String>> getInfo(ArrayList<String> _displayItem){
HashMap<String, List<String>> _itemList = new HashMap<String,List<String>>();
int items = _displayItem.size();
for(int i = 0; i < items; i++) {
String _itemName = _displayItem.get(i);
List<String> itemName = new ArrayList<>();
itemName.add("some text");
_itemList.put(_itemName,itemName);
}
return _itemList;
}}
Kindly help me create a simple alarm, nothing fancy, that wakes the phone up and triggers the activity at a certain time, even when the phone is on sleep and the application has been closed. Some people say that if the application has been closed, alarm will never trigger. But the simple alarm on any android phone goes off irrespective of whether the app is running or not. So it should work. My minimumAPI level is 11

How to stop Service Intent and cancel pending Notification

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.

Android Wear custom Notification

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).

display all pending notification in a separate view

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.

Categories

Resources