即使应用关闭,如何在特定时间每天显示通知?

问题描述 投票:4回答:2

尽管Stack Overflow之前可能已经提出过这个问题,但我仍然没有找到明确的答案。

我想每天在中午12点显示通知,例如即使应用程序关闭也是如此。我引用了这些链接:Notifications in specific time every day androidAndroid daily repeating notification at specific time of a day using AlarmManagerAndroid BroadcastReceiver on startup - keep running when Activity is in Background等等......我对Service和BroadcastReceiver之间的区别感到困惑。我应该使用哪一个?或者我应该同时使用它们?

到目前为止,我知道如何显示通知,但即使应用程序关闭,我也不知道如何每天自动显示一次。

我的代码:

public class NotifyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service created", Toast.LENGTH_LONG).show();

        Intent resultIntent = new Intent(this, HomeScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, 0);

        Notification.Builder notification = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("App Title")
                .setContentText("Some Text...")
                .setContentIntent(resultPendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT < 16) {
            notificationManager.notify(1, notification.getNotification());
        } else {
            notificationManager.notify(1, notification.build());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
    }
}

AppManifest.xml:

<service android:name=".NotifyService" />

我该如何编写代码来实现我想要的?我可以理解的任何建议或任何好的链接?

android android-intent android-service android-notifications android-alarms
2个回答
9
投票

如果我理解正确,我相信您需要使用AlarmManager设置重复报警。您还需要在设备重启时设置启动警报服务。您可以编写一个执行所需操作的方法,以便在警报运行时执行,例如显示notification。以下链接可以帮助您:


1
投票

这是更新的解决方案,它适用于Android Oreo

第1步:在MainActivityand中创建方法使用AlarmManager在指定时间设置警报。

public void sharedpref(){

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!prefs.getBoolean("FirstTime", false)) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,21);
    calendar.set(Calendar.MINUTE,47);
    if (calendar.getTime().compareTo(new Date()) < 0) calendar.add(Calendar.DAY_OF_MONTH, 1);
    Intent intent = new Intent(getApplicationContext(),NotificationReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    if (alarmManager != null) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
    }

        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean("FirstTime", true);
        editor.apply();
    }
}

我在09:47 PM发出警报

第2步:创建BroadcastReceiver以在发生警报时收听

public class NotificationReceiver extends BroadcastReceiver {

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

    NotificationHelper notificationHelper = new NotificationHelper(context);
    notificationHelper.createNotification();

   }
}

我正在创建这个名为NotificationReceiver的类并扩展BroadcastReceiver,在onReceive中有一个名为NotificationHelper的类,请不要混淆我将为后续步骤解释此类。

第3步:创建Notification类

class NotificationHelper {

private Context mContext;
private static final String NOTIFICATION_CHANNEL_ID = "10001";

NotificationHelper(Context context) {
    mContext = context;
}

void createNotification()
{

    Intent intent = new Intent(mContext , NotificationActivity.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
            0 /* Request code */, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle("Title")
            .setContentText("Content")
            .setAutoCancel(false)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

    NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }
    assert mNotificationManager != null;
    mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
       }
     }

该类处理通知

第4步:回到第2步:并调用通知类

 NotificationHelper notificationHelper = new NotificationHelper(context);
 notificationHelper.createNotification();

我希望它对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.