1

i have implement alarm manager to my application but confused because my alarm manager won't start when my application closed/died i was searching in google many suggestion in there but no one suggestion work. this my secenario

  1. open application-> automatic start service/alarm manger
  2. when application open every 10 minutes the application check to server to download data and insert to database
  3. when application close every 10 minutes the application check to server to download data and insert to database

the problem is when the application is close the service also stop. this my example code

MainActivity.java

AlarmReceiver alarm = new AlarmReceiver();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    alarm.setAlarm(this);
}

AlarmReceiver.Java

public class AlarmReceiver extends WakefulBroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

@Override
public void onReceive(Context context, Intent intent) {   

    Intent service = new Intent(context, SchedulingService.class);
    startWakefulService(context, service);
}

public void setAlarm(Context context) {
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);


     alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
              10000,
              10000, alarmIntent);

    ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);           
}

public void cancelAlarm(Context context) {
    // If the alarm has been set, cancel it.
    if (alarmMgr!= null) {
        alarmMgr.cancel(alarmIntent);
    }


    ComponentName receiver = new ComponentName(context, BootReceiver.class);
    PackageManager pm = context.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
} }

BootReceiver.java

public class BootReceiver extends BroadcastReceiver {
AlarmReceiver alarm = new AlarmReceiver();
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
    {
        alarm.setAlarm(context);
    }
}}

ScheduleService.java

public class SchedulingService extends IntentService {
public SchedulingService() {
    super("SchedulingService");
}

public static final String TAG = "Scheduling Demo";
public static final int NOTIFICATION_ID = 1;
public static final String SEARCH_STRING = "Active";
public static final String URL = "http://localhost/TMALive";
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;

@Override
protected void onHandleIntent(Intent intent) {
    String urlString = URL;
    String result ="";
    try {
        result = loadFromNetwork(urlString);
    } catch (IOException e) {
        Log.i(TAG, getString(R.string.connection_error));
    }

    if (result.indexOf(SEARCH_STRING) != -1) {
        sendNotification(getString(R.string.live_found));
        Log.i(TAG, "Your Post Live!!");
    } else {
        sendNotification(getString(R.string.no_live));
        Log.i(TAG, "Your Post Off. :-(");
    }
    AlarmReceiver.completeWakefulIntent(intent);

}


private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager)
           this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.ic_launcher)
    .setContentTitle(getString(R.string.pos_alert))
    .setStyle(new NotificationCompat.BigTextStyle()
    .bigText(msg))
    .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
private String loadFromNetwork(String urlString) throws IOException {
    InputStream stream = null;
    String str ="";

    try {
        stream = downloadUrl(urlString);
        str = readIt(stream);
    } finally {
        if (stream != null) {
            stream.close();
        }      
    }
    return str;
}


private InputStream downloadUrl(String urlString) throws IOException {

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Start the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    return stream;
}


private String readIt(InputStream stream) throws IOException {

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    for(String line = reader.readLine(); line != null; line = reader.readLine()) 
        builder.append(line);
    reader.close();
    return builder.toString();
}}

thats code work fine when application open but when application closed no notification showing and after restart also.

can you give me suggestion witch better using this approach or using service approach?

many thanks

Kenjin
  • 51
  • 1
  • 1
  • 4
  • Well, I did what the docs say here: https://developer.android.com/training/scheduling/alarms.html. And so far it works pretty well. Even when the phone is restarted or the app is not running. – Thorsten Dittmar Sep 19 '16 at 07:18
  • Some meizu phones has self energy manager that can destruct your alarm when phone turns off screen – Beyka Sep 19 '16 at 07:20
  • thats means the better is using service? but if using service how to make service triger data every 10 minute? – Kenjin Sep 19 '16 at 07:25

2 Answers2

0

Had the same problem, and in my case it turned out to be because of a stock app called 'Auto-start Manager' on the device (an ASUS phone) that I was testing on, which prevents apps to start in the background unless the user explicitly permits it. (Giving no warnings whatsoever)

Although it's a slim chance, you might want to check if similar software is running on your system if you did everything according to the book and it still doesn't work when the app is running.

Şafak Gezer
  • 3,928
  • 3
  • 47
  • 49
0

Whenever apps closed or remove from recent apps, it calls onTrimMemory() method.

You need set alarm manager again when application closed or remove from recent apps. Override following method in class which extends Application.

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    // set alarm here 
}
Anup
  • 21
  • 1
  • 3