简体   繁体   中英

Running a notification using AlarmManager

I'm using the alarm manager to request data from a server periodically. I want to display the response in a notification. However, the app crashes whenever I try to display the notification. This is the code I've written:

Main Activity

public class MainActivity extends AppCompatActivity {

    private WebView mWebview;
    private Alarm alarm;
    private PendingIntent pendingIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Intent alarmIntent = new Intent(MainActivity.this, Alarm.class);
        alarmIntent.putExtra(Alarm.NOTIFICATION_ID, 1);
        alarmIntent.putExtra(Alarm.NOTIFICATION, getNotification("HELLO"));
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    private Notification getNotification(String content) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        return builder.build();
    }
}

And the Alarm class

public class Alarm extends BroadcastReceiver 
    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification); // !!!!! CRASHES HERE
    }

I'm a complete Android newbie so any help would be appreciated.

It looks like you are attempting to set an inexact alarm that repeats every 10 seconds.

Try changing your Alarm class to the following, being sure to put in your package name, and your packageName.ActivityNameToLaunch where I have specified:

public class Alarm extends WakefulBroadcastReceiver {
     public void onReceive(final Context context, Intent intent) {
         Intent myIntent = new Intent();
         myIntent.setClassName("YourPackageName", "YourPackageName.ActivityToLaunchOnAlarmReceive");
         myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context.startActivity(myIntent);
     }
}

This is how I have a working alarm set up in one of my apps. Please note this code will launch an activity that you specify when the alarm goes off. In that activity you can have your Toast notification, or whatever you want.

Also I think you need an AlarmService class to handle the intent:

public class AlarmService extends IntentService {
    private NotificationManager alarmNotificationManager;

    public AlarmService() {
        super("AlarmService");
    }

    @Override
    public void onHandleIntent(Intent intent) {

            sendNotification("Wake up sleepyhead");

    }

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

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

        NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
                this).setContentTitle("Reminder").setSmallIcon(R.mipmap.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);  

        alarmNotificationBuilder.setContentIntent(contentIntent);
        alarmNotificationManager.notify(1, alarmNotificationBuilder.build());
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM