我尝试设置一个警报,只会在特定日期的特定时间发出一次通知。但它会在给定时间后连续发出通知。当应用程序关闭时通知无效。但是我想在后台运行通知过程。已经在清单中添加了必要的权限,并且还使用了广播接收器。 代码如下。
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
//calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.HOUR_OF_DAY, 22);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 05);
//calendar.set(Calendar.AM_PM,Calendar.PM);
final int id = (int) System.currentTimeMillis();
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent= PendingIntent.getBroadcast(MainActivity.this, id, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
// If the alarm has been set, cancel it.
/*if (alarmManager!= null) {
alarmManager.cancel(pendingIntent);
}*/
} //end onCreate
}
答案 0 :(得分:0)
不要在活动中执行此警报工作,而是使用服务,以便它在后台运行,而无需GUI的布局。这将解决您的通知问题。 你可以开始here
答案 1 :(得分:0)
检查此链接 Alarm Manager Example 并替换它 am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000 * 60 * 10,pi); 这样 am.set(AlarmManager.RTC_WAKEUP,1000 * 60 * 10,pi);
答案 2 :(得分:0)
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
//instert youre function here
}
},
50000//or any time until it happend
);
希望这对你有用......
答案 3 :(得分:0)
试试这个
Handler允许您发送和处理与线程的MessageQueue关联的Message和Runnable对象 Handler
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
//your code
handler.postDelayed(runnable, 1000);
}
};
handler.post(runnable);
答案 4 :(得分:0)
是的,我的代码已经过测试,通知没有重复。
警报管理器保留所有警报,直到重启设备。一旦重启设备(关闭然后再打开),它就会释放所有警报。所以你应该在" boot_completed"之后另外设置警报。
public class DeviceBootReceiver extends BroadcastReceiver {
private static final String TAG = "DeviceBootReceiver";
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// set the Alarm again here...
setReminderAlarm(context);
}
}
您应该在Android清单文件中注册。
<receiver android:name="com.tcalender.calendartelugu.activity.DeviceBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
3 alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);应该只执行一次。