1

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

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

谢谢

4

1 回答 1

2

您想要做的是为此使用广播通知的 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());
}

}

然后确保将其添加到您的清单中并使用您的应用程序包名称:

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

希望有帮助!

于 2013-05-16T22:31:20.090 回答