How to show local notification every hour using service

前端 未结 1 1155
攒了一身酷
攒了一身酷 2021-01-24 04:20

I want to show local notification on every hour or particular seconds using service, I have tried to implement this functionality, but I didn\'t got success.

My code is

相关标签:
1条回答
  • 2021-01-24 04:25

    Your code seems to be OK. The only thing that can be problematic is the interval 4*60*60 is too short which is 14.4 seconds.

    Moreover it seems like you're not directing the intent to a specific receiver. you should do like this:

    Calendar calendar = Calendar.getInstance();
    Intent intent1 = new Intent(MainActivity.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager)this.getSystemService(this.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60, pendingIntent);
    

    And you should catch it in:

    public class AlarmReceiver extends BroadcastReceiver{
    
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
    
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
    
        Intent notificationIntent = new Intent(context, EVentsPerform.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    
    
        NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.drawable.applogo)
                .setContentTitle("text")
                .setContentText("text")
                .setWhen(when)
                .setContentIntent(pendingIntent)
        notificationManager.notify(yourId, mNotifyBuilder.build());
    
    }
    
    }
    

    Add this to your manifest file:

     <!-- permission required to use Alarm Manager -->
     <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    
     <!-- Register the Alarm Receiver -->
     <receiver android:name="com.example.alarmmanagernotifcation.AlarmReceiver"/> 
    
    0 讨论(0)
提交回复
热议问题