我有一个包含各种日期和时间条目的数据库。我想制作一个 android 应用程序,将所有日期时间条目与当前日期和时间匹配,并在条目匹配时发出通知。最好的方法是什么?我希望循环应该每 6 小时工作一次。我应该创建一个服务吗?
我有一个 TimeAlarm 课程
public class TimeAlarm extends BroadcastReceiver {
// NotificationManager nm;
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String str = hours + ":" + minutes + ":" + seconds;
System.out.print(str);
TestAdapter tat = new TestAdapter(context);
tat.createDatabase();
tat.open();
Cursor mcurr = tat.getTestData();
if (mcurr != null)
do {
String data = mcurr.getString(4);
if (str.equals(data))
;
{
nb.setContentTitle("New Episode Released");
nb.setContentText(mcurr.getString(1));
nb.setSmallIcon(R.drawable.ic_launcher);
nb.setAutoCancel(true);
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
final Intent notificationIntent = new Intent(context,
TitleScreen.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
final PendingIntent contentIntent = PendingIntent
.getActivity(context, 0, notificationIntent, 0);
nb.setContentIntent(contentIntent);
Notification notification = nb.getNotification();
nm.notify(0, notification);
}
} while (mcurr.moveToNext());
tat.close();
}
}
然后我有这个 ShowSeries 类,我称之为 TimeAlarm 类
public void remind() {
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (5 * 1000), pendingIntent);
}
我通过它访问数据库的这个 TestAdapter 类。
public Cursor getTestData() {
try {
System.out.println("inside gettestdata");
String sql = "SELECT * FROM TV";
System.out.println("query passed");
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToFirst();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>" + mSQLException.toString());
throw mSQLException;
}
}
当我按下特定按钮时,会调用提醒功能。但之后它应该每 6 小时后连续工作。使用此代码后,我只有在按下该按钮时才会得到结果。