Make an intent kill a service - android

I'm trying to make a foreground notification for a service that has a button that when presses, will end the service. I have created the button but I have no idea what to make my intent to end the service.
public Notification getNotification(String message) {
Intent intent = new Intent(serviceContext, NotificationGenerator.class);
PendingIntent pi = PendingIntent.getActivity(serviceContext, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(serviceContext)
.setContentTitle(message)
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pi)
.addAction(R.drawable.remove_button,"End Service", endService);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
return n;
}
Intent endService = new Intent();
What should I set endService to to do so?

Related

How do i give boolean status success or not to pendingIntent in broadcast Receiver

i'm developing addAction notification from iBeacon, how do i give boolean status success or not to this actionIntent from this pendingIntent notification which will received in onReceive method in ActionReceiver.class
this is the notification method from MainActivity.class
Intent broadcastIntent = new Intent(this, ActionReceiver.class);
broadcastIntent.putExtra("action", "notif1");
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.mipmap.th_notif_logo)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.addAction(R.drawable.ic_petunjuk_icon,"Clue", actionIntent)
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(pIntentAction)
.setPriority(Notification.PRIORITY_HIGH)
.build();
this is the onReceive method in ActionReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getStringExtra("action");
if(action.equals("notif1")){
SharedPreferences preferences = context.getSharedPreferences("MYPREFS", MODE_PRIVATE);
final String nama_tim = preferences.getString("username", "Key not correct");
InserData(nama_tim, "fsrd");
Toast.makeText(context.getApplicationContext(),"Action Receiver berhasil masuk",Toast.LENGTH_SHORT).show();
}
else if(action.equals("action2")){
}
//This is used to close the notification tray
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
}
so when i got boolean status success or not, i can do something in MainActivity.class
if (actionIntent == success){
//do something
}
really appreciate your help guys..
On your MainActivity.class
Intent broadcastIntent = new Intent("action-key"); // Specify the action to your intent.
broadcastIntent.setPackage(getPackageName());
// The values you want receive in the BroadcastReceiver.
broadcastIntent.putExtra("key-action", "notif1");
broadcastIntent.putExtra("key-boolean", true);
PendingIntent actionIntent = PendingIntent.getBroadcast(
this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT)
NotificationCompat.Action notificationAction = new NotificationCompat.Action(R.drawable.ic_action, "Action Name", actionIntent)
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(this,"channelId")
.setSmallIcon(R.mipmap.ic_launcher)
.setTicker("Your Title")
.setWhen(System.currentTimeMillis())
.setContentTitle("test")
.setContentText("test")
.setAutoCancel(true)
.addAction(notificationAction) // Adds an action button to the notification
.setContentIntent(contentIntent) // Launches the intent when you click the notification.
.setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission
.setPriority(Notification.PRIORITY_HIGH)
.build();
....
....
// Instead of using your own class receiver, you have to use the default default class receiver if you want your data to reach to your MainActivity.class easily.
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == "action") {
bool result = intent.getBooleanExtra("key-boolean", false); // Your value
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("action");
registerReceiver(broadcastReceiver, intentFilter);
Have you tried using public static boolean? Can you explain exactly when do you want your boolean to be true or false?

Scheduling Notifications with broadcast reciever and actions on click

I am new to android and currently learning about notifications, there's a small app I am making which is supposed to show notification later in time and should open an activity when user taps on them. I have been looking for content all over internet but can't really understand how to do both task. I am using a broadcast receiver and here's my code
Notification.Builder builder = new Notification.Builder(getActivity());
builder.setContentTitle("Remember to return");
builder.setContentText(title);
builder.setSmallIcon(R.drawable.ic_notification);
builder.setAutoCancel(true);
//NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity());
Notification notification = builder.build();
Intent notificationIntent = new Intent(getActivity(),NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID,1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION,notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(activity,0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//long _notificationTimeInMillis = SystemClock.elapsedRealtime()+date.getTime()+getMillisFromHours(6);
long notificationTimeInMillis = SystemClock.elapsedRealtime() + 5000;
AlarmManager alarmManager = (AlarmManager)activity.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,notificationTimeInMillis,pendingIntent);
Toast.makeText(activity,"Notification Set",Toast.LENGTH_SHORT);
and for reciever
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
Currently I am able to show notifications, what changes to I have to make so that an activity (say HomeActivity.class) opens when user clicks on notification.
You need to set a pending intent on the notification itself that will open the activity:
Notification.Builder builder = new Notification.Builder(getActivity());
builder.setContentTitle("Remember to return");
builder.setContentText(title);
builder.setSmallIcon(R.drawable.ic_notification);
builder.setAutoCancel(true);
// add these lines
PendingIntent pi = PendingIntent.getActivity(
getActivity(),
REQUEST_CODE_FOR_THIS_ONE,
new Intent(getActivity(), HomeActivity.class),
0
);
builder.setContentIntent(pi);
Notification notification = builder.build();

How to ask Yes/No in notification and then launch the app and run corresponding method? Source code and screenshot attached

I have prepared a simple test app which posts a notification on a button click:
The source code from MainActivity.java creating the notification is displayed below:
Button showButton = (Button) findViewById(R.id.show);
showButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
appIntent.putExtra("my_data", 12345);
String question = getString(R.string.the_question);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, appIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentTitle(question)
.setContentText(question)
.setTicker(question)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.build();
mManager.notify(NOTIFY_ID, notification);
}
});
My question is: how to modify the notification, so that the user is asked a Yes/No question (in this case: "Do you want to open the car?") and - after she selects Yes or No to launch the same app and run a corresponding method in it (in this case: openCar() or closeCar() method).
I probably should use NotificationCompat.Action.Builder - but how exactly?
Also I am not really sure if this code is the correct code for launching an app from notification and what flags should I use:
Intent appIntent = new Intent(mContext, MainActivity.class);
appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
And finally I wonder if hardcodidng some random number in NOTIFY_ID is the correct way when posting notifications?
Here is a source code I used for notification with Login/Register action.
private void sendNotification(String message, String title) {
try {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
PendingIntent secondActivityPendingIntent = PendingIntent.getActivity(this, 0 , secondActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Intent thirdActivityIntent = new Intent(this, ThridActivity.class);
PendingIntent thirdActivityPendingIntent = PendingIntent.getActivity(this, 0 , thirdActivityIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_3d_rotation_white_36dp)
.setContentTitle(title)
.setContentText(message)
.addAction(R.drawable.ic_lock_open_cyan_600_24dp,"Login",secondActivityPendingIntent)
.addAction(R.drawable.ic_lock_pink_700_24dp,"Register",thirdActivityPendingIntent)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
To use it: simply call this method sendNotification(String yourMessage, String yourTitle)
e.g. sendNotification("Hello Message", "Hello Title")
Here is a snapshot of the output
Notify user on pending Intent.. an example is here..
public void notifyUser() {
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(HappyActivity.this, NotificationDialog.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// use the flag FLAG_UPDATE_CURRENT to override any notification already
// there
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification(R.drawable.ic_launcher,
"Question.....?????", System.currentTimeMillis());
notification.flags = Notification.FLAG_AUTO_CANCEL
| Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, "title",
"Explanation of question..", pendingIntent);
// 10 is a random number I chose to act as the id for this notification
notificationManager.notify(10, notification);
}

How to call a method or phone number using notifcation addAction

I'm trying to call this method` Or more importantly call a number when I press the addAction button.
public void call(){
Log.i(TAG,"Attempting Call "+emergecyNumber);
Intent callIntent = new Intent(Intent.ACTION_CALL);
//callIntent.setData(Uri.parse("tel:" +emergecyNumber));
startActivity(callIntent);
}`
My notifcation
public void startFallNotification(String name, String loc){
Intent intent = new Intent(); //create intent for notifcation
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification noti = new Notification.Builder(this)
.setVibrate(new long[]{1000,1000,1000,1000,1000}) //sets vibrate
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
//sets sound
.setTicker(name+" has fallen at "+loc)
.setContentTitle(name+" has fallen at "+loc)
.setContentText(n+" has fallen")
.setSmallIcon(R.drawable.ic_launcher)
.addAction(R.drawable.ic_launcher, "Call Now", null)
.setContentIntent(pIntent).getNotification();
NotificationManager notiMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notiMan.notify(0,noti);
}
You need to create a PendingIntent with the CALL action and provide that when you call addAction() on the Notification. Like this:
// This activity will be started when the user clicks on the notification
Intent intent = new Intent(); //create intent for notifcation
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Create a PendingIntent for the CALL action
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +emergecyNumber));
PendingIntent callPendingIntent = PendingIntent.getActivity(this, 0, callIntent, 0);
Notification noti = new Notification.Builder(this)
.setVibrate(new long[]{1000,1000,1000,1000,1000}) //sets vibrate
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
//sets sound
.setTicker(name+" has fallen at "+loc)
.setContentTitle(name+" has fallen at "+loc)
.setContentText(n+" has fallen")
.setSmallIcon(R.drawable.ic_launcher)
.addAction(R.drawable.ic_launcher, "Call Now", callPendingIntent)
.setContentIntent(pIntent).getNotification();

Android Notification Action not calling pending intent to service

I am trying to get my on going notification to have a button, when clicked it should call my service which is controlling audio playback.
Here is my notification with the intent
Intent intent = new Intent(context, AudioStreamService.class);
Random generator = new Random();
PendingIntent i = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(ticker)
.setNumber(number)
.setOngoing(true)
.addAction(
R.drawable.ic_action_stat_reply,
res.getString(R.string.action_reply),
i);
notify(context, builder.build());
Here is the on start for my service
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("APP ID", "APP ID - service called ");
if(isPlaying){
stop();
}
else {
play();
}
return Service.START_STICKY;
}
The log is never triggered when called from the action in the notification. But the service is used by a button in the app and works fine. Log gets called as do commands below.
Use :
PendingIntent pendingIntent = PendingIntent.getService(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
instead of :
PendingIntent pendingIntent = PendingIntent.getActivity(context, 579, intent,PendingIntent.FLAG_UPDATE_CURRENT);
^^ This is used to start an activity from the notification.

Categories

Resources