gpt4 book ai didi

安卓本地通知

转载 作者:行者123 更新时间:2023-11-29 21:50:17 24 4
gpt4 key购买 nike

我正在做的是实现本地通知。这个想法是,日期存储在手机上的 SQL 文件中,当当前日期到达 SQL 文件中的日期之前的日期时,我正在查看通过消息通知用户。

我对此进行了大量研究,并找到了与警报和服务相关的内容。我现在真的很困惑,不知道该 Root 。有人可以帮忙吗?

谢谢

最佳答案

您要做的是为此使用一个 AlarmManager 来广播通知。您不需要在数据库中设置日期并对其进行管理...只需在 AlarmManager 中设置日期即可。我为此创建了一个类,它具有设置闹钟响起时间以及接收广播然后构建通知的功能。

public class MyAlarmManager extends BroadcastReceiver {
private Context mContext;
private AlarmManager mAlarmManager;

public MyAlarmManager() {}

public MyAlarmManager(Context context) {
mContext = context;
mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
}

@Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();

//You can do the processing here.
buildNotification(context);

//Release the lock
wl.release();
}

public void setReminder(long time) {
Intent intent = new Intent(mContext, MyAlarmManager.class);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent, 0);
mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, pi); //time is in milliseconds
}

public void buildNotification(Context context) {
long[] vibrate = { 0, 100, 200, 300 };

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setVibrate(vibrate)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, YourLaunchActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ConferencesActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
int randomId = 1000303;
mNotificationManager.notify(randomId, mBuilder.build());
}

然后请务必将此添加到您的 list 中并使用您的应用程序包名称:

<receiver android:name="com.example.myapp.MyAlarmManager"></receiver>

希望对您有所帮助!

关于安卓本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com