Notification Builder (this) problems android - java

I have this object:
public void timerDistraction(final View view) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after time
Toast.makeText(getApplicationContext(),
"Button is clicked", Toast.LENGTH_LONG).show();
Notification notification = new Notification.Builder(this)
.setContentTitle("Basic Notification")
.setContentText("This is my example of basic notification")
.setSmallIcon(R.drawable.ic_launcher).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = getNotificationManager();
notificationManager.notify(0, notification);
Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notificationSound);
r.play();
}
}, 5000);
And the line
Notification notification = new Notification.Builder(this)
Has an error, presumably because of the (this)
Can anyone point me in the right direction. I've tried changing it to the function or null, but no progress. If I have just the notification code itself, without the delay, it works.

When you are in the Runnable, this became the Runnable and not the context of your Activity. Since you must pass a context as parameter, it triggers an error. To get the correct context, you can use the same way as the one you used for the Toast:
Notification notification = new Notification.Builder(getApplicationContext());
In this case, you will effectively pass your Activity context and not your Runnable.

Related

AlarmManager doesn't stop playing sound when user taps on push notification and get in app

PUSH-NOTIFICATION PROBLEM
I am building a Calendar app and I added an alarm that user can choose specific date and time. The alarm works fine. My problem is that when the notification is shown and I tap on the notification bar, I get in the app and the music play until I quit the app. The only wayI found, is to add a time delay to play for 10seconds for example, but I want to stop music on tap.
Vibrator problem
Also, the vibrator doesn't work, right now this isn't such a big problem, so if anyone can solve me at least the vibrator problem it would be very helpfuld.
My AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VibrationEffect.DEFAULT_AMPLITUDE);
String event = intent.getStringExtra("title");
String comment = intent.getStringExtra("comment");
Intent activityIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity( context,0,activityIntent,0 );
String text = "Reminder for the Event: " + "\n" + event + "\n" + "Comments: " + "\n" + comment;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "myandroid")
.setSmallIcon(R.drawable.alarm)
.setContentTitle(event)
.setContentText(text)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(text))
.setContentIntent(pendingIntent)
.setDeleteIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(123,builder.build());
Notification notification1 = builder.build();
notification1.flags |= Notification.FLAG_AUTO_CANCEL;
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (r.isPlaying())
r.stop();
}
},1000*10 );
}
}

Android call notification - Stop timer when click

I'm making a notification when a user receive a video call in my app.
My notification :
Intent intent1 = new Intent(Intent.ACTION_CAMERA_BUTTON);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent1,0);
NotificationCompat.Action action = new NotificationCompat.Action(R.drawable.ic_camera_notification,"Ok",pendingIntent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle("TITRE !!")
.setContentText("Test")
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_CALL)
.setSmallIcon(R.drawable.ic_camera_notification)
.addAction(action)
.setSound(uri)
.setAutoCancel(true)
.setVibrate(new long[] { 1000, 1000});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = builder.build();
notificationManager.notify(11,notification);
To repeat the notification until user answer (or limited time) I think to add a timer (like explain here : What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?)
But when user make a choice, I want to stop the timer. But there are no onClickListener, only Intent.
How can I do that ? Thanks
If you are using Handler like this:
// Message identifier
private static final int MSG_SOME_MESSAGE = 1234;
private Handler handler;
...
handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == MSG_SOME_MESSAGE) {
// do something
// to repeat, just call sendEmptyMessageDelayed again
return true;
}
return false;
}
});
Set the timer like this:
handler.sendEmptyMessageDelayed(MSG_SOME_MESSAGE, SOME_DELAY_IN_MILLISECONDS);
Cancel the timer like this:
handler.removeMessages(MSG_SOME_MESSAGE);

How to notify an Activity when a Service fired an action

I created a timer and I've implemented a Service that sends a notification to the user when the timer ends.
When the timer stops I play an Audio file that continues until the user stops it by clicking "OK" on a DialogFragment, but when the app is in background and I click on the notification the Sound keep going because the DialogFragment doesn't popup, What I want to know is: is it possible to notify the TimerActivity from the service so when the notification is opened I show the DialogFragment or I stop the sound?
This is my Service code:
public class ScheduledService extends IntentService {
public ScheduledService() {
super("My service");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do something, fire a notification or whatever you want to do here
Log.d("debug", "Ring Rind !");
// Build notification
// Actions are just fake
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("This is a sample notification")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Call", pIntent)
.addAction(R.drawable.ic_launcher, "More", pIntent)
.addAction(R.drawable.ic_launcher, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
I'd use Observer pattern for this as this is basically what you are looking for. On Android you can implemented it yourself (1 screen of code) or use existing implementations if you wish like EventBus like OTTO or GreenRobot's.

Displaying Notification after Background Process done Android

I am loading an HTTP request in the background using loopj HTTP CLIENT and when it is done, I want to display a "success" notification (dialog, toast, etc.)
I have the code in a seperate (non-activity) class with a static method that executes the background request. In the end, the response is in a AsyncHttpResponseHandler under a onSuccess method. In this method, I can print out the response, confirm that the request went through, save data to the sd card/ Shared Preferences, but how do I access the UI thread to display a notification?
Thanks in advance.
you can do it using a Handler, or by calling Activity.runOnUiThread(). so you either pass a Handler, or an Activity object to your static method, then in your onSuccess() method, do,
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// i'm on the UI thread!
}
}
);
or,
handler.post(new Runnable() {
#Override
public void run() {
// i'm on the UI thread!
}
}
);
I guess you mean a service as a background process. Service has many built in methods like onCreate, onStartCommand, onDestroy, etc. I suggest using a Notification, because notifications do not require a UI thread to do the job.
Create a method to generate a notification and call it after your HTML read is over.
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
You could fire a local broadcast with the message, and show a toast with a receiver.
Do this in the class doing the updates:
Intent intent = new Intent("ACTION_TOAST");
intent.putExtra("message", "Success!");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Then in any activity that might want to know about the update, do this:
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if ("ACTION_TOAST".equals(intent.getAction()) {
Toast.makeText(MyActivity.this, intent.getStringExtra("message"),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(
receiver, new IntentFilter("ACTION_TOAST"));
}
#Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
You still need to pass a context into your static method, but this works even if that context is a Service or some other context that can't show Toasts / create UI.

Remove ongoing notification from service

I have a service that create a notification when it is started.
And then ondestroy() i want it to be removed.
I just use .cancel(NOTIFICATION_ID);
It works great when it is a normal notification but when i am using ongoing event it just won't cancel it.
I did read something about that services doesn't stop if android have the resources for it, but how to overcome this?
I use this code to start the service
final Intent bg_service = new Intent(BackgroundService.class.getName());
btn_start = (Button)findViewById(R.id.btn_start);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(bg_service);
}
});
btn_stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopService(bg_service);
}
});
I use this in on create
notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"A new notification", System.currentTimeMillis());
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
Intent intent = new Intent(this, mainapp.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "...",
"...", activity);
notificationManager.notify(19314, notification);
And this in on destroy
noficationManager.cancel(19314);
I would look at doing 'ongoing' notifications a bit differently if you can. There are methods that live on Service that are dedicated to adding and removing an 'ongoing' notification.
Service.startForeground(int, Notification)
Service.stopForeground(boolean)
Perhaps you could just try calling stopForegroud(boolean) from your onDestroy() method first...

Categories