简体   繁体   中英

Need some help troubleshooting code that schedules daily notifications

I am new to android programming and just started working on my first app recently. I am trying to create a daily notification that a user would get at the same time every day. I've looked through documentation and some tutorials and came up with this. For some reason the code below does not work. It has no errors, runs just fine, but doesn't do the job and I can't seem to find the problem. There is also some code that is responsible for re-scheduling notifications when the device restarts but I don't think the problem lies there since I don't even get the initial notifications.

MainActivity.java

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

    show = (Button)findViewById(R.id.btn_show);
    show.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startAlarm(true,true);
        }
    });

    myWebView = (WebView)findViewById(R.id.webView1);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://google.com");
    myWebView.setWebViewClient(new WebViewClient());
}

private void startAlarm(boolean isNotification, boolean isRepeat) {
    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent myIntent;
    PendingIntent pendingIntent;

    // SET TIME HERE
    Calendar calendar= Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,14);
    calendar.set(Calendar.MINUTE,45);


    myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);


    if(!isRepeat)
        manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
    else
        manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}

AlarmNotificationReciever.Java

public class AlarmNotificationReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

        Intent myIntent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                0,
                myIntent,
                FLAG_ONE_SHOT );

        builder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Zodiac")
                .setContentIntent(pendingIntent)
                .setContentText("Check out your horoscope")
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentInfo("Info");

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1,builder.build());
    }
}

It should basically schedule a notification at 14:45 after pressing the button but for some reason it doesn't.

  1. Since Android Oreo, implicit broadcast receivers won't work when
    registered in the AndroidManifest.xml

    1. To use Implicit Receivers in your application, you need to define them programmatically in your code, using registerReceiver().

3.Using registerReceiver() we can programmatically register and unregisterReceiver() during the lifecycle of the activity. This way implicit receivers would only be called when our activity/application is alive and not at other times.

we working fine:

     [public class MainActivity extends AppCompatActivity {
            Button  show;
            WebView  myWebView;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

             // register custom intent filter

               *registerReceiver(new AlarmNotificationReceiver(),new IntentFilter(Intent.ACTION_BATTERY_CHANGED));*

\[enter image description here\]\[1\]
                show = (Button)findViewById(R.id.btn_show);
                show.setOnClickListener(new View.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onClick(View v) {
                        startAlarm(true,true);
                    }
                });
                myWebView = (WebView)findViewById(R.id.webView1);
                WebSettings webSettings = myWebView.getSettings();
                webSettings.setJavaScriptEnabled(true);
                myWebView.loadUrl("http://google.com");
                myWebView.setWebViewClient(new WebViewClient());
            }
            @RequiresApi(api = Build.VERSION_CODES.N)
            private void startAlarm(boolean isNotification, boolean isRepeat) {
                AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                Intent myIntent;
                PendingIntent pendingIntent;
                // SET TIME HERE
                Calendar calendar= Calendar.getInstance();
                calendar.set(Calendar.HOUR_OF_DAY,14);
                calendar.set(Calendar.MINUTE,45);
                myIntent = new Intent(MainActivity.this,AlarmNotificationReceiver.class);
                pendingIntent = PendingIntent.getBroadcast(this,0,myIntent,0);
                if(!isRepeat)
                    manager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,pendingIntent);
                else
                    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
            }
        }][1]

1)But the above code may not work in all versions ie notofication will not came oreo(8.0) and above.beacause of NotificationBuilder is depricated and background execution limits. Go to

2)Use Notification Channel .like below

use this code.hope its works fine!!!

void issueNotification() 
{ 

    // make the channel. The method has been discussed before. 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
        makeNotificationChannel("CHANNEL_1", "Example channel", NotificationManager.IMPORTANCE_DEFAULT); 
    } 
    // the check ensures that the channel will only be made 
    // if the device is running Android 8+ 

    NotificationCompat.Builder notification = 
                new NotificationCompat.Builder(this, "CHANNEL_1"); 
    // the second parameter is the channel id. 
    // it should be the same as passed to the makeNotificationChannel() method 

    notification 
        .setSmallIcon(R.mipmap.ic_launcher) // can use any other icon 
        .setContentTitle("Notification!") 
        .setContentText("This is an Oreo notification!") 
        .setNumber(3); // this shows a number in the notification dots 

    NotificationManager notificationManager = 
                (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 

    assert notificationManager != null; 
    notificationManager.notify(1, notification.build()); 
    // it is better to not use 0 as notification id, so used 1. 
}

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