Pra*_*son 17
以下代码使用Alarmmanager和BroadcastReceiver,它将帮助您实现您的需求.
在您的活动中:
Intent intent = new Intent(MainActivity.this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, REQUEST_CODE, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(am.RTC_WAKEUP, System.currentTimeInMillis(), am.INTERVAL_DAY*7, pendingIntent);
Run Code Online (Sandbox Code Playgroud)
System.currentTimeInMillis() - 表示警报将在当前时间触发,您可以以毫秒为单位传递一天的常量时间.
然后创建一个这样的Receiver类,
public class Receiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
showNotification(context);
}
public void showNotification(Context context) {
Intent intent = new Intent(context, AnotherActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, reqCode, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.android_icon)
.setContentTitle("Title")
.setContentText("Some text");
mBuilder.setContentIntent(pi);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(reqCode, mBuilder.build());
}
}
Run Code Online (Sandbox Code Playgroud)
您还必须在清单文件中注册BroadcastReceiver类,如下所示.在AndroidManifest.xml文件中,在内部标记中,
<receiver android:name="com.example.receivers.Receiver"></receiver>
Run Code Online (Sandbox Code Playgroud)
这里"com.example.receivers.Receiver"是我的包和我的接收者名字.
| 归档时间: |
|
| 查看次数: |
7403 次 |
| 最近记录: |