Ok I saw a lot of people just dismiss this question by saying
"it's reserved for OS component "
"it requires access to source"
Well I have access to the source and I can set any app or widget I want as a system app. So now how would I go about making my widget show its notification on the right side?
EDIT:
ok ppl are going in the wrong direction so ill add come context here . . .
look at ur phone . . . u see Wi-Fi signal and phone signal on the right side of the phone all the time right. I want my signal to be shown there aswell . . . along with the system signals . . I have a new hardware chip in the tablet my company is making and I have to display its signal strength constantly just like the phone signal. It is going to be integrated into the Android source of the tablet.
You might need to refer to the code of Android source code of phone status bar, at https://android.googlesource.com/platform/frameworks/base/+/android-4.3_r3.1/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBar.java
And take a look at the methods like
addIcon
updateIcon
removeIcon
It is not easy task since you have to add lots of stuff by yourself.
You'll need to modify a few places:
framework/base/core/res/res/values/config.xml, add a slot in:
<string-array name="config_statusBarIcons">
then frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java:
mService.setIcon("<your slot name>", R.drawable.yourlogo, 0, null);
mService.setIconVisibility("<your slot name>", setVisible);
That's mostly it, I'm sure you can figure out the rest on your own with some trial and errors.
I have one easy idea ie:
In manifest declare android screen orientation as landscape
and design like landscape for portrait mode
so that ur app looks portrait in landscape mode.
public class GCMIntentService extends GCMBaseIntentService {
public static final String PROJECT_ID = "4898989797";
private static final String TAG = "GCMIntentService";
ModelNotificationMessage modelNotificationMessage;
public GCMIntentService() {
super(PROJECT_ID);
Log.d(TAG, "GCMIntentService init");
}
#Override
protected void onError(Context ctx, String sError) {
// TODO Auto-generated method stub
Log.d(TAG, "Error: " + sError);
}
#Override
protected void onMessage(Context ctx, Intent intent) {
Log.d(TAG, "Message Received");
String message = intent.getStringExtra("message");
Log.d(TAG, "Message Received" + message);
sendNotification(message);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("GCM_RECEIVED_ACTION");
broadcastIntent.putExtra("gcm", message);
ctx.sendBroadcast(broadcastIntent);
}
private void sendNotification(String message) {
// this
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.notification;
CharSequence tickerText = message; // ticker-text
long when = System.currentTimeMillis();
Context context = getApplicationContext();
CharSequence contentTitle = modelNotificationMessage.getKey();
CharSequence contentText = message;
Intent notificationIntent = null;
int NOTIFICATION_ID = 9999;
NOTIFICATION_ID = CommonVariable.notification_message;
notificationIntent = new Intent(this, ViewMessages.class);
contentText = arrayList.get(0).getDescription();
tickerText = arrayList.get(0).getDescription();
// and this
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
I found some related information regarding your question on this forum...
http://forum.kde.org/viewtopic.php?t=107601
--Good day
Related
i'm building a notification that is launched with a toggle button:
toggleLigar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(toggleLigar.isChecked()){
NotificationUtil.cancelaAll(TelaCriaDesp.this);
CharSequence tickerText = "Despertador ativado!";
CharSequence title = "Você não vai perder seu ponto!";
CharSequence message = "O despertador " + despertador.getNomeDesp() + " está ativo!";
Intent intent = new Intent(TelaCriaDesp.this, TelaCriaDesp.class);
NotificationUtil.criaNotification(TelaCriaDesp.this, tickerText, title, message,
despertador.getDesp_id(), intent);
} else {
NotificationUtil.cancelaNotification(TelaCriaDesp.this, despertador.getDesp_id());
}
}
});
now i want to assign the toggle button in ON or OFF according to the notification state, if it's active (being displayed) it's ON, inactive OFF... I have tried this:
public static boolean testaNotification(int id, Context context){
Intent intent = new Intent(context, TelaCriaDesp.class);
//intent.setAction(Intent.);
PendingIntent teste = PendingIntent.getActivity(context, id, intent,
PendingIntent.FLAG_NO_CREATE);
return teste != null;
}
but it's not working, it always returns NULL...
here's my notification creation:
public class NotificationUtil {
#SuppressWarnings("deprecation")
public static void criaNotification(Context context, CharSequence tickerText, CharSequence title,
CharSequence message, int id, Intent intent){
PendingIntent aoSelecionar = PendingIntent.getActivity(context, 0, intent, 0);
Notification notification = null;
int apiLevel = Build.VERSION.SDK_INT;
if(apiLevel >= 11){
Builder montaNotification = new Notification.Builder(context)
.setContentTitle(tickerText)
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(aoSelecionar);
//montaNotification.setAutoCancel(true);
montaNotification.setOngoing(true);
if(apiLevel >= 17){
notification = montaNotification.build();
} else {
notification = montaNotification.getNotification();
}
} else {
notification = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());
notification.setLatestEventInfo(context, title, message, aoSelecionar);
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
}
NotificationManager manager = (NotificationManager)
context.getSystemService(Activity.NOTIFICATION_SERVICE);
manager.notify(id, notification);
}
From API 23 and up you can use NotificationManager method getActiveNotifications(). This returns a list of active notifications launched by your app in a form of an array.
So to check if a particular notification is active, you can just iterate over the elements of this array and compare notification ids/tags.
Read more on this method here:
NotificationManager.getActiveNotifications()
You cannot. You must track it manually, if You need.
In fact Notification is meant only to notify a user about some event. If you need to check if the notification is present - then, in fact, You need to check if the event (which the notification is about) is still valid.
In the case You described, You may persist information in the local database when creating a notification.
Add a contentIntent to the notification to be able to mark the database item appropriately when a user dismisses notification by clicking it.
Then when You need to test if the notification exists, just look for a valid row in the local database.
If You only have one simple notification of given type, You can just persist a boolean flag in a preference file without need for local database to use.
Hi i want to show all the notification in a single view .. and want to update number of notification in status bar ... its updating all info but showing number always 1.. please tell me how to solve it...
#Override
public void onReceive(Context context, Intent intent)
{
//Random randGen = new Random();
//int notify_id = randGen.nextInt();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Activity.NOTIFICATION_SERVICE);
String title = intent.getStringExtra(TableUtils.KEY_TITLE);
String occasion = intent.getStringExtra(TableUtils.KEY_OCCASION);
Notification notification =
new Notification(R.drawable.icon, "Love Cardz" ,
System.currentTimeMillis());
// notification.vibrate = new long[]{100,250,300,330,390,420,500};
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.number+=1;
Intent intent1 = new Intent(context, ThemesBrowserActivity.class);
PendingIntent activity =
PendingIntent.getActivity(context, 1 , intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, occasion, title, activity);
notificationManager.notify(1, notification);
}
You have to keep track of the count. You could extend the Application class:
public class AppName extends Application {
private static int pendingNotificationsCount = 0;
#Override
public void onCreate() {
super.onCreate();
}
public static int getPendingNotificationsCount() {
return pendingNotificationsCount;
}
public static void setPendingNotificationsCount(int pendingNotifications) {
pendingNotificationsCount = pendingNotifications;
}
}
And you should modify the onReceive:
#Override
public void onReceive(Context context, Intent intent) {
...
int pendingNotificationsCount = AppName.getPendingNotificationsCount() + 1;
AppName.setPendingNotificationsCount(pendingNotificationsCount);
notification.number = pendingNotificationsCount;
...
}
And you could reset the count when the user open the notification:
AppName.setPendingNotificationsCount(0);
This is my code, and it works. I have only tested on old Android versions thou. I suspect on newer versions the "number" badge has been made invisible, but I haven't had the chance to test it.
void notifyMsgReceived(String senderName, int count) {
int titleResId;
String expandedText, sender;
// Get the sender for the ticker text
// i.e. "Message from <sender name>"
if (senderName != null && TextUtils.isGraphic(senderName)) {
sender = senderName;
}
else {
// Use "unknown" if the sender is unidentifiable.
sender = getString(R.string.unknown);
}
// Display the first line of the notification:
// 1 new message: call name
// more than 1 new message: <number of messages> + " new messages"
if (count == 1) {
titleResId = R.string.notif_oneMsgReceivedTitle;
expandedText = sender;
}
else {
titleResId = R.string.notif_missedCallsTitle;
expandedText = getString(R.string.notif_messagesReceivedTitle, count);
}
// Create the target intent
final Intent intent = new Intent(this, TargetActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent =
PendingIntent.getActivity(this, REQUEST_CODE_MSG_RECEIVED, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Build the notification
Notification notif = new Notification(
R.drawable.ic_notif_msg_received, // icon
getString(R.string.notif_msgReceivedTicker, sender), // tickerText
System.currentTimeMillis()); // when
notif.setLatestEventInfo(this, getText(titleResId), expandedText, pendingIntent);
notif.number = count;
notif.flags = Notification.FLAG_AUTO_CANCEL;
// Show the notification
mNotificationMgr.notify(NOTIF_MSG_RECEIVED, notif);
}
It is also easy to update the notification later on: you just have to call the method again with new values. The number will be displayed in the notification icon badge if and only if it was greater than zero when the notification was created.
Similarily, the number badge won't be hidden (the number will, thou) if you set the number to a number that is less than 1. Maybe clearing the notification before re-showing it could fix it.
You have to keep track of the count. The increment that you're trying to perform on notif.number isn't working, since that state is unavailable (i.e. notif.number is always 0, then you increment it to 1). Keep track of number somewhere in your app(shared preferences, perhaps), and increment and store it there, then when you build the notification, set
notif.number = myStoredValueForWhatShouldShowInNumber;
Give that a try.
I've got an interesting (well, to me at least) issue:
I have a notification which I pop up in my app as needed. everything works great on my Galaxy S II (epic touch 4g from sprint, since there are so different models of the S II out there, I feel I need to be specific), and the notification word wraps with no problem - for example:
this is a notification, but it's too long,
so it'll show this second line on it's own.
To my horror, I realized that some android phones did NOT auto word wrap, and in fact simply cut my notification at the end of their screen, so the above message would show up as:
this is a notification, but it's too long,
obviously, this won't do. so, what can I do to make sure the entire message always shows up?
Rewrite
As we discussed before you want to force the Notifcation's tickerText to word wrap. One approach is to break the text into lines of the appropriate length and send out a notification for each one:
public class Example extends Activity {
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("Example", "Alarm received");
sendNotification();
}
}
AlarmManager alarmManager;
NotificationManager notificationManager;
AlarmReceiver alarmReceiver = new AlarmReceiver();
Notification notification = new Notification();
Intent notificationIntent;
PendingIntent pendingIntent;
int tickerIndex = 0;
List<String> tickerTexts = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Determine the screen width and density, split tickerText appropriately
String tickerText = "A tickerText that is long enough to cause a word wrap in portrait.";
tickerTexts.add(tickerText.substring(0, 35));
tickerTexts.add(tickerText.substring(35));
notificationIntent = new Intent(this, Example.class);
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
notification.icon = android.R.drawable.star_on;
sendNotification();
registerReceiver(alarmReceiver, new IntentFilter("Generic"));
}
#Override
protected void onDestroy() {
unregisterReceiver(alarmReceiver);
super.onDestroy();
}
public void sendNotification() {
Log.v("Example", "Send Notification " + tickerIndex);
notification.tickerText = tickerTexts.get(tickerIndex);
notification.setLatestEventInfo(this, "Title", "Text " + tickerIndex, pendingIntent);
notificationManager.cancel(0);
notificationManager.notify(0, notification);
tickerIndex++;
if(tickerIndex < tickerTexts.size()) {
Log.v("Example", "Setting up alarm");
PendingIntent alarmPending = PendingIntent.getBroadcast(this, 0, new Intent("Generic"), 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, alarmPending);
}
}
}
However you can see I skipped an integral part of the set up: I assumed the length of the text that would fit, I didn't calculate it. In order to determine an appropriate break point you need to calculate the screen's width, the font's scaled size, and the density. You also would need factor in the fact that "!!!" might be shorter than "www" depending on the font and that the user could switch between landscape and portrait... You could look in the source code to see how a generic Android breaks up the tickerText.
Anyway, forcing a tickerText to word wrap might be more complex than condensing your original String or sending angry letters to the "non-wrapping" phone manufacturers.
I'm working on an application to display the battery status of then phone/tablet. I have it running and working as it is, but somehow the application is 'killed' when the screen is turned off.
The strange thing is though that is is killed on my LG phone, but not on my Galaxy Tab when the screen is off/locked.
The source code is as following:
public class BatteryLevelActivity extends Activity {
private TextView batterLevel;
CharSequence tickerText = "No need to charge at the moment";
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.main);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
batterLevel = (TextView) findViewById(R.id.batteryLevel);
};
private void notif(int level) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "BatteryWatch";
CharSequence contentText = "Remaining charge level is " + level + "%";
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
batterLevel.setText("Battery level is at " + level + "%\n\n"
+ tickerText);
notif(level);
tickerText = "";
}
};
}
Somehow I think that I should have a method that is called something like 'onScreenOff' or maybe 'onScreenOn' and then the application could be reloaded, but I'm open to suggestions as to how to keeo it running when the screen is off/locked.
Thanks in advance
You probably want to consider using a Service because you want this running long term, the developer guide here explains more. Also (although I cannot find the link) want to tell Android that it should restart your app if it has to kill it. I cannot remember exactly what this is called
** Additional Info **
I gave slightly false information in the above. I believe you can make a Service re-start after Android has killed it but NOT an Activity. In the link above for the developer guide for Service it's detailed there. It's called starting a service as sticky, see the sub-section Extending the Service Class.
I want to notify user of mobile as particular event take place,Using notification bar icon.
Is there any way to do the same?
use this method where you required.its worked for me properly.
Hope it will solve your problem.
private void notification(Context c)
{
// TODO Auto-generated method stub
EfficientAdapter1 e1=new EfficientAdapter1(c);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) e1.no(ns);
//int icon = R.drawable.xyz;//your image
CharSequence tickerText = "ticker text";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, Text, when);
Context context = c;
CharSequence contentTitle = "your title";
CharSequence contentText = " your text";
Intent notificationIntent = new Intent(context, ViewAllSMS.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
final int HELLO_ID = 1;
notification.flags = Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(HELLO_ID, notification);
}
Use the Android NotificationManager (http://developer.android.com/reference/android/app/Notification.html)
Refer the app dev guide example - http://developer.android.com/guide/topics/ui/notifiers/notifications.html
After setting the required properties and calling the notify method, the status bar would show up the notification which you require.
Omkar Ghaisas
You can always go for pop ups. they are neat and gives you chance to notify the user. Other wise you can use toast also. Just the problem in toast is that it appears for some time and then disappears, so if somehow user misses that toast he may never know about toast. or say notification. You can see example here