My notification get restart when i click on it by Status bar
when i start my app it stream audio from server and show a notification until i don't clear it from status bar so my problem is when i click on my app notification it restart the activity and stop the streaming music..
so please suggests me solution for to stop restarting app again from notification and i want to show notification which stick on notification bar upto i exit from app
Also I want to Show pause and Play button on Notification so please help me that too
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pi= PendingIntent.getActivity(this, 0, in`enter code here`tent, 0);
String body = " Welcome to streaming ";
String title = "radio";
Notification n = new Notification(R.drawable.png, body, System.currentTimeMillis());
n.setLatestEventInfo(this , title, body, pi);
n.defaults=Notification.DEFAULT_ALL;
nm.notify(uniid,n);`
Add this in to your manifest file inside the activity which you are starting through notification, as if it is already running it won't be restarted again ..
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden" // fixes orientation
Don't allow to destroy your application on back press :
#Override
public void onBackPressed()
{
moveTaskToBack(true);
//super.onBackPressed(); // comment this line else your app will be destroyed
}
Related
I have reviewed a lot of information on this issue, but no one can solved it.
On android 7.0 devices,when using NotificationManager to send more than 5 messages, all messages will be collapsed.
Please click on the image to see the message is collapsed.
When I click on this collapsed notification bar message, my app will be rebooted into the login activity even if my app is logged in and running in the foreground.This is terrible.If I click on a single notification bar message, then it will enter the activity normally.
How to set the notification bar message to not collapse or when I click on the collapsed notification bar message, do not restart the app.
this is my code:
Intent notifyIntent;
PendingIntent appIntent;
notifyIntent = new Intent(context, TestActivity.class);
notifyIntent.putExtra("content", contentJson);
appIntent = PendingIntent.getActivity(context,
noticeId, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "program").setAutoCancel(true)
.setSmallIcon(iconId)
.setContentTitle(notifyTitle)
.setDefaults(Notification.DEFAULT_ALL)
.setNumber(noticeId)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setGroupSummary(false)
.setContentIntent(appIntent);
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
builder.setColorized(true);
Notification myNoti = builder.build();
myNoti.flags = NotificationCompat.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL;
if (noticeId > 40) {
noticeId = 0;
notificationManager.cancelAll();
}
notificationManager.notify(noticeId, myNoti);
I set TestActivity
android:launchMode="singleTop"
I found the problem, not what I thought. App is not restarted.Only LoginActivity was recreated once and placed on the top of the stack.I am worried that other people have the same thoughts as me and think that the APP has been restarted,So I won’t change this question.I hope to help people who have this problem.I will put the solution below.
When you click on the collapsed notification bar message, assume your LoginAtivity has been recreated.You need to write the following code in the onCreate of LoginActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isTaskRoot()) {
finish();
return;
}
setContentView(R.layout.activity_main_menu);
}
isTaskRoot() will detect if this class is at the root of the stack.If not, then finish.
Note that if you have logic in onDestory, use isTaskToot() to determine,for example:
#Override
protected void onDestroy(){
super.onDestroy();
if (isTaskRoot()) {
//your code
}
}
I am developing an Android app. I my app, I am trying to show process notification to user. But what I want is I do not want notification opening an Activity or removed when it is get clicked. What I am doing is I am showing notification when a user click a button. Notification will saying "Transferring data". Notification is fired from receiver.
So when user click a button, receiver is called. But I do not want that notification removed or closed when user click it. I do not want to show any activity as well. I just want to close itself when data processing finish.
This is my receiver that show notification when button is clicked
public class GalleryImageUploadReceiver extends BroadcastReceiver {
private Context context;
private NotificationCompat.Builder notification;
#Override
public void onReceive(Context pContext, Intent intent) {
this.context = pContext;
showProcessNotification();
doAsyncTaskInBackground()
}
public void doAsyncTaskInBackground()
{
//I want to close it here after task is finished
}
public void showProcessNotification()
{
try{
notification = new NotificationCompat.Builder(context);
notification.setAutoCancel(true);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setWhen(System.currentTimeMillis());
notification.setTicker("Transferring data...");
notification.setContentTitle(context.getResources().getString(R.string.app_name));
notification.setContentTitle("Transferring data...");
notification.setOngoing(true);
notification.setDefaults(Notification.FLAG_ONGOING_EVENT);
Intent i = new Intent(context.getApplicationContext(), MainActivity.class);//In this line, I do not want to open any activity
i.putExtra("start", OfficeMainActivity.FRAGMENT_NOTIFICATIONS);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(),0,i,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager)context.getApplicationContext().getSystemService(context.getApplicationContext().NOTIFICATION_SERVICE);
nm.notify(1,notification.build());
}
catch (Exception e)
{
}
}
public void uploadImages(Context context,Intent intent)
{
onReceive(context,intent);
}
}
Receiver is called in button click event like this
GalleryImageUploadReceiver receiver = new GalleryImageUploadReceiver();
receiver.uploadImages(getBaseContext(),new Intent());
As you can see, I set ongoing to true because I want to make it undismissable. But the problem is it is closed because an activity is opened.
These are what I want:
I do not want to open an activity when notification is clicked.
I only want it close itself. How can I do that?
Instead can show option dialog with buttons?
But I do not want that notification removed or closed when user click it.
remove this
notification.setAutoCancel(true);
I do not want to open an activity when notification is clicked.
remove this
Intent i = new Intent(context.getApplicationContext(), MainActivity.class);//In this line, I do not want to open any activity
i.putExtra("start", OfficeMainActivity.FRAGMENT_NOTIFICATIONS);
PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(),0,i,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
I suggest you read up on notification documentation. This is pretty straightforward stuff.
How can I close if self please?
you can "close" a notification manually with
nm.cancel(1); // if 1 is your notification id.
Instead can show option dialog with buttons?
Instead of doing that you should just present the buttons inside the notification.
I've followed a tutorial and implemented GCM push notification on my existing app. I've set Main activity to show notification. User receives a notification, clicks on it and notification display on Main activity. The problem is on app relaunch it shows notification every time.
Main Activity
public void registerGCM() {
....
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, uname, uemail, regId);
}
}
Im calling this function on onCreate of Main activity to register app. This process is working fine.
Here's the BoradcaseReceiver code in Main activity outside of onCreate function.
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
WakeLocker.acquire(getApplicationContext());
Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
WakeLocker.release();
}
};
It should only show notification once when user clicks it (this works fine), but its also showing notification every time use launch the app. How do i prevent this?
Please let me know if im not clear enough.
Any help will be highly appreciated.
Thanks!
If i understood you correctly your missing this documentation
add this attrs into your manifest between activity tags for your result activity i.e MainActivity (for more information check link above)
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:taskAffinity=""
i can't see your notification receiver class so make sure you are setting resultIntent flags like
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
note: dont forget to give every notification an unique id
So I'm working on a simple music player. The music player as it names states, can play a song, pause playback, forward to next song, go back to previous song, and stop playback completely. When you play a song, there will be a notification displayed with the Artist Name, and the Song Name; this notification also has three buttons (Actions): Stop, Pause an Next.
What I'm having issues with is making sure that when either action is clicked, the playback control related to the Action is triggered, and well, I have absolutely no idea on how to do that. I searched the Android Notification: http://developer.android.com/guide/topics/ui/notifiers/notifications.html but It does not clarifies, or dedicates too much info on Notification Actions.
Here is a simple action for instance (which should be associated with the "Next" button click on the notification: Note: All of the code described below is written under the following package: com.deadpixels.light.player and the Activity is called: PlayerActivity
public void nextSong() {
if (position == songs.size() -1) {
Toast.makeText(this, "No more songs on queue", Toast.LENGTH_SHORT).show();
if(mPlayer.isPlaying()) {
return;
}
else {
buttonPlay.setImageResource(R.drawable.button_play);
}
return;
}
else {
position++;
playSong(songs.get(position));
}
}
Here is what I tried to do:
Intent nextIntent = new Intent(KEY_NEXT);
PendingIntent nextPendingIntent = createPendingResult(0, nextIntent, 0);
Where the action for the NextIntent is:
public static final String KEY_NEXT = "com.deadpixels.light.player.PlayerActivity.nextSong";
and then I add that to the Notification via addAction():
mBuilder.addAction(R.drawable.not_action_next, "Next", nextPendingIntent);
Do you guys know what else I could try? Using what I explained above does nothing at all, the notification shows up, and has three action buttons, but clicking on them does nothing for me.
At one point I thought maybe if I added the intent filters with the action names, but then I thought, well, they are all on the same namespace, why should I?
I've solved this problem using broadcasts. For example, to send a broadcast that advances to the next song, you can use the following:
Intent nextIntent = new Intent(KEY_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
Then, register a BroadcastReceiver within your Activity:
IntentFilter filter = new IntentFilter();
filter.addAction(KEY_NEXT);
// Add other actions as needed
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(KEY_NEXT)) {
nextSong();
} else if (...) {
...
}
...
}
}
registerReceiver(receiver, filter);
If you're using a service to manage background playback, then you'll want to register the BroadcastReceiver in the service instead of the activity. Be sure to store the receiver instance somewhere so that you can unregister it when the activity or service is shut down.
I have implemented C2DM in the application and everything seems to work properly when app is running. But in case app is not running and push message is received. On tap of push message in the notification panel a separate activity is called. This activity can be called PushMsgHandlerActivity. From this activity one can be redirected to other activity within the application. Say user clicks on a button in PushMsgHandlerActivity and is redirected to Activity A which is the launcher activity. From here, if user presses back button then would go to the view which was there before opening up the push message. If now the home button is kept pressed and we select the app from there then instead of starting launcher activity the app starts the PushMsgHandlerActivity again. The reason I suppose is since that's the activity that was started first for the application.
Anyways of starting launcher activity in this case.
Please note that this issue occurs only when push message is received and application is not running. Otherwise the app works and behaves properly.
If you never want the user to be returned to the PushMsgHandlerActivity, try turning off history for that Activity, as described here, by adding the flag android:noHistory="true" to your manifest file in the section for that activity. This should only bring the user to that Activity when you take them there (through clicking a push message).
Here is a simple example that seems to do what you want. It has two activities, a NotifyMainActivity which immediately starts a notification, and a HandleNotificationActivity which is called when you click the notification.
NotifyMainActivity:
public class NotifyMainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this,
HandleNotificationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(1, notification);
}
}
HandleNotificationActivity:
public class HandleNotificationActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.handler);
}
public void startMain(View view) {
Intent i = new Intent(this, NotifyMainActivity.class);
startActivity(i);
finish();
}
}
handler.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="startMain"
android:text="Main" />
</LinearLayout>
I have tested by starting the main activity, which creates a notification. Then press the back button, go to your home screen. Click the notification, which starts the handler activity. Then click the Main button, and press back. It will not take you back to the handler since it called finish() on itself. I hope this example can clear things up a bit.