Android AlarmManager with BroadcastReceiver and Service not starting - java

I'm trying to start a service scheduled for a specific date. My problem is that the intent which should start the service, doesn't do it.
This is my Helper which should start the service
public class AlarmHelper {
public static void createAlarm(Context ctx, TRANSAZIONE_MENSILE tm) {
int giorniDifferenza = calcolaGiorni(tm.getMonthDay());
int secondiDifferenza = calcolaSecondi();
int minutiDifferenza = calcolaMinuti();
int oreDifferenza = calcolaOre();
Intent alarmIntent = new Intent(ctx, AlarmService.class);
alarmIntent.putExtra("secondi", secondiDifferenza);
alarmIntent.putExtra("minuti", minutiDifferenza);
alarmIntent.putExtra("ore", oreDifferenza);
alarmIntent.putExtra("giorni", giorniDifferenza);
alarmIntent.putExtra("requestCode", tm.getRequestCode());
ctx.startService(alarmIntent);
}
//other methods not relevant in the process
}
And here is the AlarmService
public class AlarmService extends Service {
Alarm alarm = new Alarm();
public void onCreate(){
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Bundle extras = intent.getExtras();
int sec = extras.getInt("secondi");
int min = extras.getInt("minuti");
int hour = extras.getInt("ore");
int days = extras.getInt("giorni");
int requestCode = extras.getInt("requestCode");
alarm.setAlarm(this, sec, min, hour, days, requestCode);
return START_STICKY;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
And finally this is the BroadcastReceiver
public class Alarm extends BroadcastReceiver {
private static final int SECS = 1000;
private static final int MINS = 60000;
private static final int HOURS = 3600000;
private static final int DAYS = 86400000;
#Override
public void onReceive(Context ctx, Intent intent) {
PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//qui metto il codice
//todo codice
//prendo il request code
int requestCode = intent.getIntExtra("requestCode", -1);
if (requestCode != -1) {
// cancello l'allarme che si sa mai
cancelAlarm(ctx, requestCode);
// ora bisogna anche che la transazione sia salvata
AlarmHelper.resolveAlarm(ctx, requestCode);
// ora ricreo l'allarme nuovo per il mese prossimo
AlarmHelper.restartAlarm(ctx, requestCode);
}
wl.release();
}
public void setAlarm(Context ctx, int sec, int min, int hours, int days, int requestCode) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctx, Alarm.class);
i.putExtra("requestCode", requestCode);
PendingIntent pi = PendingIntent.getBroadcast(ctx, requestCode, i, 0);
int tempoInMilli = 0;
tempoInMilli += (SECS * sec);
tempoInMilli += (MINS * min);
tempoInMilli += (HOURS * hours);
tempoInMilli += (DAYS * days);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tempoInMilli, pi);
}
public void cancelAlarm(Context context, int requestCode) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
The Intent simply doesn't reach the service, how should I fix it? Any help will be appreciated

Related

How to use Broadcast receiver in non-static service class

Hello I created Broadcast Receiver in the Service class to receive application notifications but it doesn't receive any intents from Notification. When I make the broadcast receiver static, the problem is solved but at this time I cannot access the elements of the non-static upper class. I have to solve this without making it static.
My Code:
public class BackgroundService extends Service {
private final int TASK_DELAY = 0;
private final int TASK_PERIOD = 5 * 1000;
int NOTIFICATION_ID = 1;
private Context context;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static Timer timer;
private PendingIntent test;
private int runRate;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//User pressed a notifiacition button
Log.w(TAG, "onReceive: Recived" );
}
// constructor
public MyReceiver(){
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public static Timer getTimer() {
return timer;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service has been started!", Toast.LENGTH_SHORT).show();
context = getApplicationContext();
timer = new Timer();
runRate = 0;
builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("KolBoost")
.setContentText("Arkaplan servisi etkinleştirildi!")
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
Intent close = new Intent(getBaseContext(), BackgroundService.class);
close.setAction("CLOSE_SERVICE");
PendingIntent closeServiceIntent = PendingIntent.getBroadcast(getBaseContext(), 0, close, 0);
Intent i2 = new Intent(getBaseContext(), BackgroundService.class);
i2.setAction("BOOST_MEMORY");
PendingIntent boostIntent = PendingIntent.getBroadcast(getBaseContext(), 0, i2, 0);
Intent launch = new Intent(getBaseContext(),BackgroundService.class);
launch.setAction("OPEN_MANAGER");
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, launch, 0);
builder.setContentIntent(contentIntent);
builder.addAction(0, "Clear Memory", boostIntent);
builder.addAction(0, "Exit", closeServiceIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
test = PendingIntent.getActivity(getBaseContext(), NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
//I'm adding actions to intentFilter.
filter.addAction(close.getAction());
filter.addAction(i2.getAction());
filter.addAction(launch.getAction());
//Registering Receiver with intentFilter
registerReceiver(myReceiver,filter);
super.onCreate();
}
#Override
public void onDestroy() {
timer.cancel();
notificationManager.cancelAll();
Log.d(TAG, "onDestroy: Destroyed");
super.onDestroy();
}
}

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());

Android service timer crash

I'm developing an app. In it user can input his friend's information - name and date of birth. When information is added, a service should start which should count how much time left and send a notification, when friend is having a birthday soon. Service takes info from database. When I add information, service just crashes. Here's my service code
Timer timer = new Timer();
DB2 db;
Cursor cursor;
Calendar x = Calendar.getInstance();
int y = x.get(Calendar.YEAR);
int m = x.get(Calendar.MONTH) + 1;
int d = x.get(Calendar.DAY_OF_MONTH);
int h = x.get(Calendar.HOUR_OF_DAY);
int min = x.get(Calendar.MINUTE);
int s = x.get(Calendar.SECOND);
Handler handler;
NotificationManager nm;
int l, p, a, i, month, hours, minutes, seconds, m22, d22, v, g, t;
int[] k = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
class UpdateTimeTask extends TimerTask{
public void run(){
MS2.this.runOnUiThread(new Runnable() {
#Override
public void run() {
db.open();
cursor = db.getAllData();
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
int d110 = cursor.getInt(cursor.getColumnIndex("day")); //here it should do some manipulations with every item in DB.
}
while (cursor.moveToNext());//takes next item
}
}
});
cursor.close();
}
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
public void onCreate() {
super.onCreate();
handler = new Handler();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//db = new DB2(this);
//db.open();
}
public void not() {
Intent resultIntent = new Intent(this, TEST2.class);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
int mNotificationId = 001;
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
db = new DB2(this);
db.open();
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
timer.schedule(new UpdateTimeTask(), 0, 1000);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
When I have my code like this
class UpdateTimeTask extends TimerTask{
public void run(){
db.open();
cursor = db.getAllData();
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
int d110 = cursor.getInt(cursor.getColumnIndex("day")); //here it should do some manipulations with every item in DB.
}
while (cursor.moveToNext());//takes next item
}
cursor.close();
}
}
There's no crash. Just no notification

Passing data from Activity to Service

I have a problem while passing String to a Service from Activity. What I am trying to do is to pass different Strings each time I call Service. I use Intent (putExtra() method each time). The problem is that each time it shows the first String that I passed. Is there a way to implement that?
Here is my Activity, Broadcast Receiver, Service
public class MainActivity extends Activity implements View.OnClickListener{
private PendingIntent pendingIntent;
private EditText event;
private Button submit, date, time;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int myYear = 2014;
private int myMonth = 8;
private int myDay = 16;
private int myHour = 6;
private int myMinute = 30;
private List<String> events;
private List<Calendar> dateTimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
event = (EditText)findViewById(R.id.event);
submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(this);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(this);
time = (Button)findViewById(R.id.time);
time.setOnClickListener(this);
events = new ArrayList<String>();
dateTimes = new ArrayList<Calendar>();
//List<Calendar> events = new ArrayList<Calendar>();
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_DATE) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return datePickerDialog;
}else {
TimePickerDialog timePickerDialog = new TimePickerDialog(this, myCallBack1, myHour, myMinute, true);
return timePickerDialog;
}
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
myYear = year;
myMonth = month;
myDay = day;
}
};
TimePickerDialog.OnTimeSetListener myCallBack1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
myHour = hour;
myMinute = minute;
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.date:
showDialog(DIALOG_DATE);
break;
case R.id.time:
showDialog(DIALOG_TIME);
break;
case R.id.submit:
String eventS = event.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth);
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.DAY_OF_MONTH, myDay);
calendar.set(Calendar.HOUR_OF_DAY, myHour);
calendar.set(Calendar.MINUTE, myMinute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, BR.class);
myIntent.putExtra("event", eventS);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
event.setText("");
break;
}
}
public class BR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
intent.getExtras().getString("event");
myIntent.putExtra("event", intent.getStringExtra("event"));
context.startService(myIntent);
Log.i("myLogs", "BR started");
}
}
public class MyService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
String event = intent.getExtras().getString("event");
Notification notification = new Notification(R.drawable.ic_launcher, "This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), event, event, pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
A service can't be stopped until it's finish. You have to wait that your current service finish to send other data. You can collect all your strings and send them all together or wait until your background service finish

Android Kitkat how to fix return_sticky bug in service

I found several posts regarding the return_sticky problem when using KitKat.
It seems like that the service can be killed and don't come back even when return_sticky.
I'm talking about a background service, not a foreground service.
I've tried several approaches but everything seems to fail. Heres a bit of code for demonstrating. After a while it gets killed and it won't come back:
public class RestPushService extends Service {
#Override
public void onDestroy() {
MainApplication.getDevice().writeBoolean("REST_PUSHSERVICE_RUNNING", false);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if ((intent != null) && (intent.getBooleanExtra("ALARM_RESTART_SERVICE_DIED", false))) {
if (MainApplication.getDevice().readBoolean("REST_PUSHSERVICE_RUNNING", false)){
ensureServiceStaysRunning();
return START_STICKY;
}
}
MainApplication.getDevice().writeBoolean("REST_PUSHSERVICE_RUNNING", true);
/** doing other stuff like creating a thread **/
return START_STICKY;
}
private void ensureServiceStaysRunning() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int restartAlarmInterval = 20 * 60 * 1000;
final int resetAlarmTimer = 2 * 60 * 1000;
final Intent restartIntent = new Intent(this, RestPushService.class);
restartIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
restartIntent.putExtra("ALARM_RESTART_SERVICE_DIED", true);
final AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Handler restartServiceHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
sendEmptyMessageDelayed(0, resetAlarmTimer);
}
};
restartServiceHandler.sendEmptyMessageDelayed(0, 0);
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(), this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
}
Now another receiver which gets called when the device starts.
public class myReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null || action.equals("com.myapp.START_ALARM")) {
if (MainApplication.getDevice().hasInternet()) {
if (!MainApplication.getDevice().hasServiceRunning(RestPushService.class)) {
context.startService(new Intent(context, RestPushService.class));
} else {
Log.d(TAG, "RestPushService was aready running. Do nothing");
}
}
}
}
public void startRepeating(Context context) {
if (alarmManager == null) alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("com.myapp.START_ALARM");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 30, pi); // Millisec * Second * Minute
}
public void stopRepeating(Context context) {
Intent intent = new Intent("com.myapp.START_ALARM");
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.cancel(sender);
}
}
I've truncated much code because I think it is not relevant. I removed all try catches and null initializations to make sure it's easily readable. So what may be caused the "don't come back" crap?
I refer also to START_STICKY does not work on Android KitKat

Categories