簡體   English   中英

需要一些幫助來解決安排每日通知的代碼

[英]Need some help troubleshooting code that schedules daily notifications

我是 android 編程的新手,最近才開始開發我的第一個應用程序。 我正在嘗試創建用戶每天在同一時間收到的每日通知。 我查看了文檔和一些教程並提出了這個。 由於某種原因,下面的代碼不起作用。 它沒有錯誤,運行得很好,但不能完成工作,我似乎找不到問題所在。 還有一些代碼負責在設備重新啟動時重新安排通知,但我認為問題不存在,因為我什至沒有收到初始通知。

主活動.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);
}

警報通知接收器.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());
    }
}

它應該基本上在按下按鈕后的 14:45 安排通知,但由於某種原因它沒有。

  1. 由於 Android Oreo,隱式廣播接收器在以下情況下將無法工作
    在 AndroidManifest.xml 中注冊

    1. 要在應用程序中使用隱式接收器,您需要在代碼中使用 registerReceiver() 以編程方式定義它們。

3.使用 registerReceiver() 我們可以在活動的生命周期內以編程方式注冊和取消注冊Receiver()。 這樣,隱式接收器只會在我們的活動/應用程序處於活動狀態時被調用,而不會在其他時間被調用。

我們工作正常:

     [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)但以上代碼可能不適用於所有版本,即通知不會出現在奧利奧(8.0)及以上版本。因為 NotificationBuilder 已被棄用且后台執行限制。

2)使用通知渠道。像下面

使用此代碼。希望它工作正常!!!

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. 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM