Alarm Doesn't work when app is closed - java

Basically, I am trying to build an alarm app which has some buttons with some predefined Date and Time. I have tried using AlarmManager and broadcast receiver in the first place but didn't work. So, I used foreground service with alarmManager but still, the alarm doesn't fire when the app is destroyed. I am a newbie. I tried searching the internet but I had no luck. Hope there is a lot of people here to help me out. Thanks in Advance.
Here I am just trying to set only one alarm for testing. Otherwise, I am using a variable as request code for multiple alarms.
AndroidManifest.xml
<receiver android:name=".AlarmReceiver" />
<activity
android:name=".Activity.PlayerDetailsActivity"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity android:name=".Activity.FixtureActivity" />
<service android:name=".MyService"/>
MyService.java
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
Log.e("service","service");
long longExtra = intent.getLongExtra(Constants.ALARM_TIME, 0000);
//Testing Area Start
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(longExtra);
int mMin = calendar.get(Calendar.MINUTE);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
Log.e("hour min month day"," "+mHour + " : "+mMin+" month : "+mMonth+" "+" Date : "+mDay+" ");
String currentDateTime=getDeviceDateTime();
Log.e("CurrentdateTime",""+currentDateTime);
Log.e("longExtra",""+longExtra);
//Testing Area End
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel(CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("dfdf")
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentText("dfdfd").build();
startForeground(3, notification);
}
/*Intent alertIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Log.d("I",""+longExtra);
alarmManager.set(AlarmManager.RTC_WAKEUP, 6000000, PendingIntent.getBroadcast(getApplicationContext(), 0, alertIntent,
PendingIntent.FLAG_ONE_SHOT));*/
AlarmManager manager= (AlarmManager)getSystemService(ALARM_SERVICE);
Intent myIntent;
myIntent = new Intent(getApplicationContext(),AlarmReceiver.class);
myIntent.putExtra("check",true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
Long finalTime =longExtra-System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);
}
else
manager.set(AlarmManager.RTC_WAKEUP,longExtra,pendingIntent);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Alarmreceiver.java
public class AlarmReceiver extends BroadcastReceiver
{
public static final String CHANNEL_ID = "47";
#Override
public void onReceive(Context context, Intent intent)
{
intent = new Intent(context, SplashActivity.class);
intent.putExtra("not",true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(context,CHANNEL_ID);
notificationCompat.setSmallIcon(R.drawable.ic_notifications_black_24dp);
notificationCompat.setContentTitle("My Noticiation");
notificationCompat.setContentText(getPreferences(context).getDateTime());
notificationCompat.setContentIntent(pendingIntent);
notificationCompat.setSound(alarmSound);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel name", importance);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
Notification notification = notificationCompat.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(100,notification);
Toast.makeText(context, "Alarm Working", Toast.LENGTH_SHORT).show();
}
}

you have to start your service so then it can set alarm and fire reciever
start it like this from your activity class
Intent intent=new Intent(this,MyService.class);
startService(intent);

Consider using JobScheduler as a persistence mechanism. It is wakeful and handles the wake locks for you. Only downside it's for Android SDK >= 21 (Lollipop).
There's also a new friend in town that does the backward compatibility for you: WorkManager and will work with all version of Android, even below Lollipop.

Intent myIntent;
myIntent = new Intent(this, AlarmReceiver.class);
myIntent.putExtra("check",true);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
=============================
Would you change your above code like this ?
Intent myIntent;
myIntent = new Intent(this , MyService.class);
myIntent.setAction("REQUEST_FROM_ALARM_MANAGER");
PendingIntent pendingIntent = PendingIntent.getForegroundService(this,0,myIntent,0);
====================================================
And Service class
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mContext = this;
Log.e(TAG, "onStartCommand " + intent);
if(intent == null) {
return START_NOT_STICKY;
}
if("REQUEST_FROM_ALARM_MANAGER".equals(intent.getAction())){
// show Notification here for your foreground service
}
return START_NOT_STICKY;
}

You have to start a service that survive to your app, you can see here how to do it

Related

How to set multiple alarms firing distinct notifications for each in Android

I am trying to develop an application in which the user can create more than 1 alarms for the same time ,say, 09:48. And for this time, each alarm has to create its own notification which leads the user to an activity when the notification is clicked. The other alarms which were scheduled at the same time must keep ringing until their notifications are clicked. Now, I am able to create alarms for different times and get their corresponding notifications which lead to an activity in which the user can dismiss or snooze the alarm. However, when I schedule more than one alarm for the same time, only 1 alarm is ringing and the other one gets lost. I share my code pieces at the below.
public void schedule(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmBroadcastReceiver.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(context, alarmId, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
alarmManager.setExact(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
alarmPendingIntent
);
In my broadcastReceiver class:
private void startAlarmService(Context context, Intent intent) {
Intent intentService = new Intent(context, AlarmService.class);
Log.println(Log.DEBUG, "DEBUG", "************Alarm Broadcast Receiver**********");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intentService);
} else {
context.startService(intentService);
}
}
In my AlarmService :
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
mediaPlayer.setLooping(true);
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, RingActivity.class);
int requestCode = new Random().nextInt(Integer.MAX_VALUE);
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, notificationIntent, 0);
//String alarmTitle = String.format("%s Alarm", intent.getStringExtra(TITLE));
int notificationId = new Random().nextInt(Integer.MAX_VALUE);
Notification notification = new NotificationCompat.Builder(this, String.valueOf(notificationId))
.setContentTitle("PASS1")
.setContentText("PASS2")
.setSmallIcon(R.drawable.pill)
.setContentIntent(pendingIntent)
.build();
mediaPlayer.start();
long[] pattern = { 0, 100, 1000 };
vibrator.vibrate(pattern, 0);
startForeground(1, notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
vibrator.cancel();
}
in this code
startForeground(1, notification);
you are using 1 as the id.
If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
So the second alarm notification with the same id (because you are using a fixed value of 1) is replacing the old one

How to trigger a launch Activity intent when my app is closed on Android 10/Q?

I am trying to create an app that will open another app at a specified time. To do this, I used an AlarmManager that starts a service. It works just fine if my app is open when the alarm is triggered. I get a notification that the service started, and the other app opens. However, if my app is in the background (after pressing the home button), and the alarm triggers, I get a notification that the service started, but the other app does not launch. What am I doing wrong? I am testing this on a Pixel 3 emulator running API level 29 (Android 10/Q).
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int REQUEST_CODE=101;
public static int aHour;
public static int aMinute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setAlarm() {
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, amReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, aHour);
calendar.set(Calendar.MINUTE, aMinute);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
//Some code that sets aHour and aMinute
//Some code that triggers setAlarm()
}
amReciever.java
public class amReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, launcherService.class);
ContextCompat.startForegroundService(getApplicationContext(), i);
}
}
launcherService.java
public class launcherService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("App is launching.")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
Intent launcher = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.example.app");
if (launcher != null) {
startActivity(launcher);
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<service android:name=".launcherService"
android:enabled="true"
android:exported="true" />
As of Android 10 (API level 29), you cannot start activities from the background anymore.
There are a number of exceptions to this rule that may or may not apply to your given scenario.
If none of the exceptions apply, you might want to consider displaying a high-priority notification, possibly with a full-screen Intent.

Scheduling Notifications with alarm manager

I know this has been asked before but I still have not found a clear answer because the previous answers are rather old. I followed a few tutorials, tried a few different ways to even show a notification. Nothing has worked and I think my issue is that I am failing to understand how to use the notification channels. All the tutorials I have followed are from before Oreo so I haven't seen anything of use and the google developer snippets are not helping either.
So the last tutorial I followed (or rather copied) said to do this:
This class constructs the notification with an alarm manager reminder
public class NotificationService {
public static final int DAILY_REMINDER_REQUEST_CODE = 100;
public static final String TAG = "Service";
private static Context context;
public static void setContext(Context inContext) {
context = inContext;
}
public static void setReminder(Context context, Class<?> cls, int hour, int min) {
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
// cancel already scheduled reminders
cancelReminder(context, cls);
if (setcalendar.before(calendar))
setcalendar.add(Calendar.DATE, 1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
DAILY_REMINDER_REQUEST_CODE, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context, Class<?> cls) {
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
public static void showNotification(Context context, Class<?> cls, String title, String content) {
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(cls);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(DAILY_REMINDER_REQUEST_CODE, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, createNotificationChannel());
Notification notification = builder.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
.setSound(alarmSound)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setChannelId("10")
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(DAILY_REMINDER_REQUEST_CODE, notification);
}
This class is the broadcast receiver to trigger the notification
public class NotifyPublisher extends BroadcastReceiver {
public static final String TAG = "Publisher";
private SharedPreferences SP;
#Override
public void onReceive(Context context, Intent intent) {
SP = context.getSharedPreferences("com.STIRlab.ema_diary", Context.MODE_PRIVATE);
if (intent.getAction() != null && context != null) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
// Set the alarm here.
Log.d(TAG, "onReceive: BOOT_COMPLETED");
int hour = SP.getInt("hour", 0);
int minute = SP.getInt("minute", 0);
NotificationService.setReminder(context, NotifyPublisher.class, hour, minute);
return;
}
}
Log.d(TAG, "onReceive: ");
//Trigger the notification
NotificationService.showNotification(context, MainActivity.class,
"30 Days", "Don't forget your daily journal entry");
}
}
and this is how I am trying to trigger it in my MainActivity
SP.edit().putInt("hour", 14).apply();
SP.edit().putInt("minute", 06).apply();
NotificationService.setReminder(MainActivity.this, NotifyPublisher.class, 14,06);
and yes I registered it in my manifest
<receiver android:name=".Helpers.NotifyPublisher"
android:enabled="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Nothing shows up and I am not sure why.

Using JobScheduler for time based notifications

I need to show the user a notification at the same time every day (based on a user selecting the time it is shown). With API 25 and earlier I can use AlarmManager without a problem. However with API 26 (Oreo) it will crash my app if the app is in the background for more than a few minutes. Nothing I've done seems to prevent AlarmManager crashing after about a minute of the app being in the background.
Based on what I have seen online the only solution is to use a JobScheduler, but there doesn't seem to be anyway to have a JobScheduler start at a certain time and then recur every day. (I can have it run at a certain time by calling setOverrideDeadline or I can make it recurring by calling setPeriodic, but calling both throws and exception.)
This is my code for the JobScheduler (I have it set to recur every 15 seconds for testing, but I also want to be able to start it at a certain time):
private void setReminders(){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_BOOT_COMPLETED) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECEIVE_BOOT_COMPLETED }, 613);
return;
}
SharedPreferences sharedPreferences = this.getSharedPreferences(getString(R.string.shared_pref_file_name), ContextWrapper.MODE_PRIVATE);
boolean showReminder = sharedPreferences.getBoolean(getString(R.string.shared_pref_reminder_active_key), false);
int hour = sharedPreferences.getInt(getString(R.string.shared_pref_reminder_hour_key), 21);
int minute = sharedPreferences.getInt(getString(R.string.shared_pref_reminder_minute_key), 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
long startUpTime = Calendar.getInstance().getTimeInMillis() + 10000; //calendar.getTimeInMillis() + 10000;
JobInfo.Builder builder = new JobInfo.Builder( 613, new ComponentName(getPackageName(), SefiraReminderJobService.class.getName()));
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE)
.setOverrideDeadline(15000)
.setRequiresDeviceIdle(false)
.setRequiresCharging(false)
.setPersisted(true);
builder.setPeriodic(Math.max(15000, JobInfo.getMinPeriodMillis()));
JobScheduler jobScheduler = (JobScheduler) getSystemService( Context.JOB_SCHEDULER_SERVICE );
if(jobScheduler.schedule(builder.build()) == JobScheduler.RESULT_FAILURE ) {
Log.w("MainActivity.setReminders", "Something went wrong when scheduling the reminders" );
}
}
This is my JobIntentService class:
public final class ReminderJobService extends JobIntentService {
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
private static int NOTIFICATION_ID = 1234;
private static String NOTIFICATION_CHANNEL_ID = "my-reminder-channel";
private Notification notification;
#Override
protected void onHandleWork(#NonNull Intent intent) {
Context context = this.getApplicationContext();
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Reminders", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("My Reminders");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
notification = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_launcher_foreground)
//.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
//.setTicker("ticker value")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM))
.setContentTitle("Reminder")
.setContentText("Reminder Message").build();
notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
notification.ledARGB = 0xFFFFA500;
notification.ledOnMS = 800;
notification.ledOffMS = 1000;
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
try {
notificationManager.notify(NOTIFICATION_ID, notification);
} catch (Exception ex){
ex.printStackTrace();
}
}
}
My AndroidManifest contains the following:
<service android:name="ReminderJobService"
android:permission="android.permission.BIND_JOB_SERVICE"></service>
As well as:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
How can I send a recurring notification each day at a specific time on Android 26/8.0/Oreo even when the app is in the background?
This workable decision but with deprecated logic:
public scheduleEvent(int id, long scheduleTime) {
final PendingIntent pendingIntent = pendingIntent(id);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, scheduleTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, scheduleTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, scheduleTime, pendingIntent);
}
private PendingIntent pendingIntent(int id) {
final Intent intent = new Intent(app, EventReceiver.class);
intent.setAction("some event " + id);
return PendingIntent.getBroadcast(context, 10, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Create EventReceiver don't forget add it in AndroidManifest
public class EventReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
final ComponentName comp = new ComponentName(context.getPackageName(), EventService.class.getName());
startWakefulService(context, intent.setComponent(comp));
}
}
Create EventService, also add it to the AndroidManifest
public class EventService extends IntentService {
#Override
protected void onHandleIntent(final Intent intent) {
//Your logic here
}
}

Stop service with PendingIntent

I have an Ongoing notification on my radio app and I already managed to start my main activity from the notification but now I'm trying to add a button to the notification to stop the streaming service.
This is my notifaction method inside the service:
#SuppressWarnings("deprecation")
private void createNotification() {
int myIconId = R.drawable.ic_pause;
Intent mIntent = new Intent(context, StreamingService.class);
Notification notification;
Bundle bundle = new Bundle();
bundle.putInt("list", list);
PendingIntent stopIntent = PendingIntent.getService(context, 0, mIntent, 0) ;
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
0, new Intent(getApplicationContext(), MainActivity.class)
.putExtras(bundle), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification();
notification.tickerText = station.getRadioName();
notification.icon = R.mipmap.ic_launcher;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(getApplicationContext(),
station.getRadioName(), null, pi);
} else {
notification = new NotificationCompat.Builder(context)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(station.getRadioName())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(
context.getResources(),
R.mipmap.ic_launcher))
.addAction(myIconId,"STOP", stopIntent)
.setOngoing(true).setContentIntent(pi).build();
}
startForeground(NOTIFICATION_ID, notification);
}
This is my OnStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
task = new ProgressTask();
task.execute();
return START_NOT_STICKY;
}
I did the Intent and the PendingIntent to start the service, but how can I set the service to stopSelf() using a PendingIntent?
I'm stuck at this for days, thanks in advance for the help.
in your OnStartCommand use this
if(intent.getAction().equals("STOP"))
stopSelf();
JRowan put me in the right direction, thanks man.
I added this line to my notification method:
mIntent.setAction("STOPME");
And this is my onStartCommand now:
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction()!=null && intent.getAction().equals("STOPME")){
stopSelf();
return START_NOT_STICKY;
}
else {
task = new ProgressTask();
task.execute();
return START_NOT_STICKY;
}
}

Categories

Resources