android 如何显示一个通知,每天在特定的时间,即使应用程序已关闭?

k10s72fa  于 2023-02-11  发布在  Android
关注(0)|答案(3)|浏览(281)

虽然这个问题以前可能在堆栈溢出中被问过,但我仍然没有找到一个明确的答案。
我想每天中午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();
    }
}
    • 应用程序清单. xml:**
<service android:name=".NotifyService" />

我应该怎样写我的代码来完成我想要的?有什么建议或任何好的链接,我可以理解?

rlcwz9us

rlcwz9us1#

这是更新的解决方案,它的工作Android奥利奥

**第1步:**在MainActivity中创建一个方法,并使用AlarmManager在指定时间设置警报。

public void myAlarm() {
  
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 21);
    calendar.set(Calendar.MINUTE, 47);
    calendar.set(Calendar.SECOND, 0);
    
    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);

  }
  
}

我把闹钟设为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, NOTIFICATION_CHANNEL_ID);
    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();

注册广播接收器转到您的Androidmanifest文件并注册广播接收器

<receiver
    android:name=".NotificationReceiver"></receiver>

有关更多信息,请参阅谷歌的this指南
希望对你有帮助。

nfeuvbwi

nfeuvbwi2#

如果我没理解错的话,我认为你需要使用AlarmManager设置一个循环报警。你还需要设置在设备重启时启动报警服务。你可以写一个方法,这样它就可以在报警运行时执行,例如show notification。下面的链接应该会对你有所帮助:

hgc7kmma

hgc7kmma3#

1.创建一个包含您的代码的方法,您将在其中定义时间或您希望显示通知的时间。需要从您希望用户请求通知的位置调用此方法。

public void getNotification () {

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));

    alarmManager.cancel(pendingIntent);

    Calendar calendar = Calendar.getInstance();
    Calendar now = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 30);
    calendar.set(Calendar.SECOND, 00);
    if (now.after(calendar)) {
        Log.d("Hey","Added a day");
        calendar.add(Calendar.DATE, 1);
    }

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}

1.创建一个Notification_receiver类,它将扩展Broadcast Receiver,您将在此处定义您的Channel Id。这适用于API 25及更高版本

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

//Created By Prabhat Dwivedi
public class Notification_receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder;
        PendingIntent pendingIntent;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("Your App Name", "You app Package Name", NotificationManager.IMPORTANCE_HIGH);
            String channel_Id = channel.getId();
            CharSequence channel_name = channel.getName();
            Log.e("Notification_receiver", "channel_Id :" + channel_Id);
            Log.e("channel_name", "channel_name :" + channel_name);

            channel.setDescription("Make entry of today's spending now");      
            notificationManager.createNotificationChannel(channel);
        }

        builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.yourapp_logo)
                .setChannelId("Your app Name is your Channel Id")
                .setContentTitle("Your title")
                .setContentText("Your Description")
                .setAutoCancel(true);

        // Under this you will find intent it is going to define after clicking notification which activity you want to redirect
        Intent repeatingIntent = new Intent(context, HomePage.class);
        pendingIntent = PendingIntent.getActivity(context, 100, repeatingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        notificationManager.notify(100, builder.build());
    }
}

相关问题