Search code examples
androidandroid-asynctaskalarmmanager

Asynctask that is set with alarmmanager fails when the application is closed on android


I have a very well working ASyncTask when my application is open but you know when you hold that home button on the phone and close applications by sliding them? it crashes.

my AlarmReceiver class

 public class Alarm-Receiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent)
{
    final Context errorContext = context;
    final UP refUP = new UP(); //just an activity for my toast

    class NotifRequest extends AsyncTask<String, Void, String[]> {
        String NotifUrlStr = String.format(errorContext.getString(R.string.notification_url), Main.Text);

        @Override
        protected String[] doInBackground(String... params) {
            String[] On = new String[2];
            String onProd = "";
            String sonOnTar = "";


            try {
                JSONTokener onTokener = new JSONTokener(Sources.httpConnGet(NotifUrlStr).toString());
                JSONArray onArray=new JSONArray(onTokener);


                JSONObject json_obj_on = onArray.getJSONObject(0);

                onProd = json_obj_on.getString("on");
                if(onProd .equals("0") == false) {
                sonOnTar = json_obj_on.getString("sonon");
                }

            } catch (Exception e) {

                refUP.runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(errorContext, "Error!", Toast.LENGTH_LONG).show();
                      }
                    });
                CancelAlarm(errorContext);
            }

            On[0] = onProd;
            On[1] = sonOnTar;
            return On;
        }

        @Override
        protected void onPostExecute(String[] onRes) {

            String onSay = onRes[0];
            String onTar = onRes[1];

            if (onSay.equals("0") && onSay != null) {
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(errorContext)
                .setSmallIcon(R.drawable.akilli_launcher)
                .setContentTitle("New")
                .setContentText("new");

                Intent resultIntent = new Intent(errorContext, UPSiparisler.class);

                        PendingIntent resultPendingIntent =
                                PendingIntent.getActivity(
                                        errorContext,
                                        0,
                                        resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT
                                        );

                        mBuilder.setContentIntent(resultPendingIntent);


                        int mNotificationId = 001;

                        NotificationManager mNotifyMgr = 
                                (NotificationManager) errorContext.getSystemService(Context.NOTIFICATION_SERVICE);

                        mNotifyMgr.notify(mNotificationId, mBuilder.build());

            }

            super.onPostExecute(onRes);
        }

    }


    NotifRequest notReq = new NotifRequest();
    notReq.execute();

}

public void SetAlarm(Context context)
{
    AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmNotifReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10*1000, pi); // Millisec * Second
}

public void CancelAlarm(Context context)
{
    Intent intent = new Intent(context, AlarmNotifReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}


 }

What should I do for this to work even after the application is closed and not keep showing the Toast "error"

Thanks in advance.


Solution

  • in your activity you should try cancelling also your AsyncTask when the Activity moves to stopped state, like this:

      @Override
      public void onStop() {
            super.onStop();
            notReq.cancel(true); 
      }
    

    I assume when the activity is not visible then you don't need your AsyncTask to finish.