Is possible create a permanent notification of battery level starting from this code?:
public void onCreate(Bundle savedInstanceState) {
...
this.registerReceiver(this.myBatteryReceiver , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
...
}
private BroadcastReceiver myBatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
//here you can use level as you wish.
}
};
And this is an example of a notification.
private void CheckNoti(){
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
service.this);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("Context");
notificationBuilder.setTicker("TickerText");
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);
Intent notificationIntent = new Intent(this, service.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notificationBuilder.setContentIntent(contentIntent);
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(1,
notificationBuilder.build());
} }
I have to create a permanent notification with the battery level if possible. How can i do it?
Use the ongoing flags : http://developer.android.com/reference/android/app/Notification.Builder.html#setOngoing%28boolean%29
The user will not be able to cancel the notification so please don't forget to remove it when it's not useful anymore.
For toggle in it, you need to add a PreferenceActivity or a PreferenceFragment to your app. Then add a checkboxPreference : http://developer.android.com/guide/topics/ui/settings.html
In your code, you can now toggle this particular setting :
boolean permanent = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("permanent", false);
if(permanent) {
notificationBuilder.setOngoing(true);
}
Related
I am developing a flashLight app and I faced a problem in notification which is : When I press the notification text I want to turn of flash and close the whole app , How can I modified the notification method to do that ??
I tried to make anthor activity and put turn of and close app methods in it, but it does not work .
please help and thanks in advance .
this is my notification method
public void getNotification()
{
Intent intent = new Intent();
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
If you use the same Activity, then the onCreate method will be called again. You can send one extra with your Intent that indicates it is an Intent generated from the click of notification. In your Activity onCreate, check for this extra and call finish() if it is present.
public void getNotification() {
Intent intent = new Intent(this, FlashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("origin", "notification");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent , PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentIntent(pIntent)
.setContentTitle(res.getString(R.string.notification_title))
.setContentText(res.getString(R.string.notification_text))
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true)
.setTicker(getString(R.string.notification_ticker_msg));
// Build the notification:
Notification notification = builder.build();
// Get the notification manager:
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Publish the notification:
final int notificationId = 0;
notificationManager.notify(notificationId, notification);
}
And in your onCreate method in FlashActivity check the extra.
#Override
public void onCreate(Bundle savedInstanceState) {
...
if("notification".equals(getIntent().getStringExtra("origin"))) {
finish();
}
}
I believe you can use finish() on your Activity when the notification ils pressed.
EDIT: How to close any activity of my application by clicking on a notification?
You want to use PendingIntent.
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("FINISH",true);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
// Build the notification:
Notification notification = builder.build();
//rest of your methods to show notification
In your MainActivity update depending on your code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
#Override
public void onNewIntent(Intent intent){
setContentView(R.layout.activity_main);
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("FINISH"))
{
finish();
}
}
}
I have a notification that, when I click on it, opens up my app. But my app opens up in the background and the notification drawer is still visible. My notification itself is canceled and removed, but the drawer still exists on top of everything.
The notification class looks like this:
public MyNotification(final Context context) {
this.context = context;
remoteView = new RemoteViews(context.getPackageName(), R.layout.notification);
notification = new Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.build();
notification.flags = Notification.FLAG_NO_CLEAR;
notification.priority = Notification.PRIORITY_MAX;
remoteView.setOnClickPendingIntent(R.id.container, getIntent(ACTION_OPEN_APP));
notification.bigContentView = remoteView;
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, notification);
}
private PendingIntent getIntent(String action) {
Intent receiveIntent = new Intent(context, NotificationReceiver.class);
receiveIntent.setAction(action);
return PendingIntent.getBroadcast(context, 0, receiveIntent, 0);
}
And my receiver looks like this:
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equalsIgnoreCase(AudioPlayerNotification.ACTION_OPEN_APP)) {
Intent openAppIntent = new Intent(context, MyActivity.class);
openAppIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
context.startActivity(openAppIntent);
}
}
I also have a base Activity that removes the notification when launching the activity. What am I missing?
Prathibhas suggested solution did not the trick, but pointed me in the right direction. The trick was to send the broadcast
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
since I'm using a broadcast receiver for the actions on the notification. The answer was provided here:
Clicking Android Notification Actions does not close Notification drawer
I have created a custom layout notification using remoteview. Problem I'm facing is, How to autoCancel the notification once the user touches it.
I did try few things, but none is giving desired result.
Find Code below:
RemoteViews remoteView = new RemoteViews(this.getPackageName(), R.layout.notification_layout);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setSmallIcon(R.drawable.ic_launcher);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, RQST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
remoteView.setOnClickPendingIntent(R.id.btnNotification, pIntent);
builder.setAutoCancel(true);
builder.setContent(remoteView);
Notification notify = builder.build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notiManager.notify(NOTY_ID, notify);
For others who have a custom layout and want auto cancel to work,
If clicking anywhere on notification is ok, then don't use remoteView.setOnClickPendingIntent. Because any view with OnClick Listener overrides the notification main OnClick Listener.
Use setContentIntent instead:
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle("title");
builder.setContentText("contect");
builder.setSmallIcon(#smallicon);
builder.setWhen(#when);
builder.setContent(remoteViews);
builder.setContentIntent(onClickPendingIntent); // use this
builder.setAutoCancel(true);
The way I achieved this is by creating BroadcastReceiver which controls button clicks from Notification. Create something like this :
public class NotificationButtonListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int action = intent.getIntExtra("mode", -1);
switch (action) {
// do some things depending on action if there are more stuff to do
}
}
}
Don't forget to add your BroadcastListener to your manifest file:
<receiver android:name=".NotificationButtonListener">
And you can create a helper class for creating and cancelling notification:
public class NotificationHelper {
private static final int NOTIFICATION_ID = 5;
private static NotificationManager mNotificationManager = null;
public static void showNotification(Context context) {
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
contentView.setOnClickPendingIntent(R.id.btn_close, closePendingIntent);
Intent mMainIntent = new Intent(context, MainActivity.class);
mMainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent mMainPendingIntent = PendingIntent.getActivity(context, 555, mMainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setTicker("Playing")
.setContent(contentView)
.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_av_play)
.setContentIntent(mMainPendingIntent);
Notification notification = mBuilder.build();
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
public static void cancelNotification() {
if (mNotificationManager != null) {
mNotificationManager.cancelAll();
}
}
}
And using that class in your NotificationButtonListener you can call NotificationHelper.cancelNotification(); .
Hope this helps you!
I'm stuck in a creation of a notification..Just want display the battery level in the status bar(notifications bar)The notification has been permanent. This is part of code:
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
String[] status = {
"Level: "+level
. . .
};
NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,"Level",System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(context, MainActivity.class);
PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0);
notification.setLatestEventInfo(getApplicationContext(), +level+"%", penInt);
notifi.notify(215,notification);
}
};
Is it correct? Is there something else to add for example in the manifest? I don't have a specified class for the notification so i wrote in this way this line: Intent i = new Intent(context, MainActivity.class); but i don't know if it's correct.
Yes, you need to add :
<uses-permission android:name="android.permission.BATTERY_STATS" />
More information here :
Get battery level only once using Android SDK
My app plays music and when users open notifications screen by swiping from the top of the screen ( or generally from the bottom right of the screen on tablets ), I want to present them a button to stop the currently playing music and start it again if they want.
I am not planning to put a widget on the user's home screen, but just into notifications. How can I do this?
You can create an intent for the action (in this case stop playing) and then add it as an action button to your notification.
Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_snooze, getString(R.string.snooze),
snoozePendingIntent);
Please refer to the Android documentation.
I will try to provide a solution that I have used and most of the music player also use the same technique to show player controls in notification bar.
I am running a service which is used to manage Media Player and all its controls. Activity User control interacts with Service by sending Intents to the service for example
Intent i = new Intent(MainActivity.this, MyRadioService.class);
i.setAction(Constants.Player.ACTION_PAUSE);
startService(i);
TO receive intents and perform action in Service class I am using following code in onStartCommand method of Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.Player.ACTION_PAUSE)) {
if(mediaPlayer.isPlaying()) {
pauseAudio();
}
}
Now to exact answer to your question to show notification with playing controls. You can call following methods to show notification with controls.
// showNotification
private void startAppInForeground() {
// Start Service in Foreground
// Using RemoteViews to bind custom layouts into Notification
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.notification_status_bar);
// Define play control intent
Intent playIntent = new Intent(this, MyRadioService.class);
playIntent.setAction(Constants.Player.ACTION_PLAY);
// Use the above play intent to set into PendingIntent
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
// binding play button from layout to pending play intent defined above
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setImageViewResource(R.id.status_bar_play,
R.drawable.status_bg);
Notification status = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
status = new Notification.Builder(this).build();
}
status.flags = Notification.FLAG_ONGOING_EVENT;
status.icon = R.mipmap.ic_launcher;
status.contentIntent = pendingIntent;
startForeground(Constants.FOREGROUND_SERVICE, status);
}
Hope this really helps you. And you will be able to achieve what you want. Have a Happy Coding :)
// It shows buttons on lock screen (notification).
Notification notification = new Notification.Builder(context)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.NotIcon)
.addAction(R.drawable.ic_prev, "button1",ButtonOneScreen)
.addAction(R.drawable.ic_pause, "button2", ButtonTwoScreen)
.....
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(1)
.setMediaSession(mMediaSession.getSessionToken())
.setContentTitle("your choice")
.setContentText("Again your choice")
.setLargeIcon(buttonIcon)
.build();
Please refer this for more details Click here
tested, working code with android Pie. These all go inside the same service class.
Show a notification:
public void setNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("a", "status", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("notifications");
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
else
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Receiver.service = this;
Notification.MediaStyle style = new Notification.MediaStyle();
notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Notification")
.addAction(R.drawable.close_icon, "quit_action", makePendingIntent("quit_action"))
.setStyle(style);
style.setShowActionsInCompactView(0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
notification.setChannelId("a");
}
// notificationManager.notify(123 , notification.build()); // pre-oreo
startForeground(126, notification.getNotification());
}
Helper function:
public PendingIntent makePendingIntent(String name)
{
Intent intent = new Intent(this, FloatingViewService.Receiver.class);
intent.setAction(name);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
return pendingIntent;
}
To handle the actions:
static public class Receiver extends BroadcastReceiver {
static FloatingViewService service;
#Override
public void onReceive(Context context, Intent intent)
{
String whichAction = intent.getAction();
switch (whichAction)
{
case "quit_action":
service.stopForeground(true);
service.stopSelf();
return;
}
}
}
You'll need to update your manifest too:
<receiver android:name=".FloatingViewService$Receiver">
<intent-filter>
<action android:name="quit_action" />
</intent-filter>
</receiver>
I think that beside Ankit Gupta answer, you can use MediaSession (API > 21) to add native mediaController view :
notificationBuilder
.setStyle(new Notification.MediaStyle()
.setShowActionsInCompactView(new int[]{playPauseButtonPosition}) // show only play/pause in compact view
.setMediaSession(mSessionToken))
.setColor(mNotificationColor)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setUsesChronometer(true)
.setContentIntent(createContentIntent(description)) // Create an intent that would open the UI when user clicks the notification
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setLargeIcon(art);
Source: tutorial
you can alse create custom view and display it in the notificcation area , first answer here is great.
you can add button as below and can perform action on that button also i have done for me as below please check.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setAutoCancel(true)
.setContentTitle(name)
.setContentText(body)
.setGroupSummary(true)
.addAction(android.R.drawable.ic_menu_directions, "Mark as read", morePendingIntent);
//morePendingIntent(do your stuff)
PendingIntent morePendingIntent = PendingIntent.getBroadcast(
this,
REQUEST_CODE_MORE,
new Intent(this, NotificationReceiver.class)
.putExtra(KEY_INTENT_MORE, REQUEST_CODE_MORE)
.putExtra("bundle", object.toString()),
PendingIntent.FLAG_UPDATE_CURRENT
);
I don't know if this is the right way or not, but it works.
Create a BroadCastReceiver class to receive the data when button is pressed.
public class MyBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String log = "URI: " + intent.toUri(Intent.URI_INTENT_SCHEME);
Log.d("my", "LOG:::::::" + log);
}
}
Now in any activity where you want to create the notification -
Intent intent = new Intent();
intent.setAction("unique_id");
intent.putExtra("key", "any data you want to send when button is pressed");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
Now use this pending intent when you are creating the notification and lastly you need to register this broadcast in order to receive it in MyBroadCastReceiver class.
BroadcastReceiver br = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter("unique_id");
registerReceiver(br, filter);
Now if you want to do certain things when the button is pressed, you can do so in the onReceive() method in MyBroadCastReceiver class.