0

I am trying to make an application for my school that includes a background service that will download a student's grades, and assignment history. The service is called every hour by an AlarmManager, and it works, but only as long as the device is powered on. As soon as the device is turned on (from a state of hibernation; the device is not completely shut down), the AlarmManager triggers the service. This is the code of the BroadcastReceiver, which includes the AlarmManager:

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.support.v4.content.WakefulBroadcastReceiver;

public class ServiceAlarmReceiver extends WakefulBroadcastReceiver {    

private final String TAG = "com.example.ahsandroidapplication";

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

    Log.i(TAG, "Broadcast received");
    Intent gradeNotificationServiceIntent = new Intent(context, GradeNotificationService.class);
    //context.startService(gradeNotificationServiceIntent);
    startWakefulService(context, gradeNotificationServiceIntent);
}

public static void setAlarm(Context context){

    System.out.println("Service started");

    long alertTime = System.currentTimeMillis() + 1000 * 60 * 60;
    Intent alertIntent = new Intent(context, ServiceAlarmReceiver.class);

    alertIntent.setAction("com.example.ahsandroidapplication.servicealarmbroadcast");

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    //alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(context, 1, alertIntent, 
    //      PendingIntent.FLAG_UPDATE_CURRENT));
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, 1000 * 3600, PendingIntent.getBroadcast(context, 
            GradeNotificationService.SERVICE_ALARM_BROADCAST_ID, alertIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT));


}

public static void cancelAlarm(Context context)
{
    Intent intent = new Intent(context, ServiceAlarmReceiver.class);

    intent.setAction("com.example.ahsandroidapplication.servicealarmbroadcast");

    PendingIntent sender = PendingIntent.getBroadcast(context, 
            GradeNotificationService.SERVICE_ALARM_BROADCAST_ID, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);
}
}

Because the broadcast is received only when the phone is turned on, I believe the problem lies in the receiver.

There is another problem with the service. It is supposed to send a push notification whenever a new grade is posted, but they are never being sent.

Here is the code for the service class:

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;

public class GradeNotificationService extends IntentService {

private Context context;

public GradeNotificationService() {
    super("GradeNotificationService");
    // TODO Auto-generated constructor stub
}

public static final int SERVICE_ALARM_BROADCAST_ID = 0;

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub

    System.out.println("Grade notification services started");
    context = getApplicationContext();
    final Intent completeWakefulIntent = intent;

    if(gradesChanged()){

        getAssignments();
    }

    ServiceAlarmReceiver.completeWakefulIntent(completeWakefulIntent);
}


private boolean gradesChanged() {

//Massive blocks of code that will take you forever to read

}

private void getAssignments(){


//Massive blocks of code that will take you forever to read
//It is in this method that sendNotification() is used to send a notification
//(at least that's what it's supposed to be doing)


}

private void sendNotification(String title, String message){

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

    mBuilder.setSmallIcon(R.drawable.ic_launcher);
    mBuilder.setContentTitle(title);
    mBuilder.setContentText(message);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
    mBuilder.setAutoCancel(true);

    Intent resultIntent = new Intent(context, MainInterface.class);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);
    mBuilder.setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = 
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(1, mBuilder.build());

}

private boolean networkIsAvailable() {

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    // return netInfo != null && netInfo.isConnectedOrConnecting();

    NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    return netInfo != null && netInfo.isConnectedOrConnecting()
            || mWifi.isConnected();

}

}

Can anyone tell me what I can do to make this service run when the phone is asleep, or why it is not sending any notifications? Any help is appriciated.

Edit:

This is most of the manifest. The target sdk is 21 and the minimum is 11:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="21" />

<application
    android:allowBackup="true"
    android:label="@string/app_name" 
    android:icon="@drawable/ic_launcher">

    <service 
        android:name="com.example.ahsandroidapplication.GradeNotificationService"
        android:enabled="true" >
       <intent-filter>
           <action android:name="com.example.ahsandroidapplication.ServiceAlarmReceiver" />
       </intent-filter>
    </service>

    <receiver android:name=".ServiceAlarmReceiver"
        android:enabled="true">   
      <intent-filter>
         <action android:name="com.example.ahsandroidapplication.servicealarmbroadcast"></action>
      </intent-filter>
    </receiver>

    <receiver android:name=".BootReceiver"
    android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"></action>
        </intent-filter>
    </receiver>

    <activity
        android:name="MainInterface"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name="MainLogin"
              android:label="@string/app_name">

    </activity>

    <service android:enabled="true"
         android:exported="false"
         android:isolatedProcess="false"
         android:label="@string/app_name"
         android:name="AspenManager" >
    </service> 

</application>
1
  • Please post the <receiver> element from your manifest for ServiceAlarmReceiver. Also, what version of Android are you testing this on, and what is your targetSdkVersion? Oct 6, 2015 at 23:50

1 Answer 1

0

"Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested."

http://developer.android.com/reference/android/app/AlarmManager.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.