我想将通知的构建延迟到例如1分钟,我该怎么办?我试图插入一个处理程序并postDelaying它但我得到了多个错误。
public void customizedOnClick (View view){
String ticker = textTicker.getText().toString();
String title = textTitle.getText().toString();
String body = textBody.getText().toString();
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setTicker(ticker);
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle(title);
notification.setContentText(body);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
//Builds notification and issues it
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
答案 0 :(得分:0)
请务必导入正确的处理程序:
导入android.os.Handler;
创建处理程序和runnable。 runnable将是您在延迟后执行的代码。
private Handler handler = new Handler();
private NotificationCompat.Builder notification;
private static final int uniqueID = 12345;
private EditText textTicker;
private EditText textTitle;
private EditText textBody;
public void customizedOnClick (View view) {
if(TextUtils.isEmpty(textTicker.getText()
|| TextUtils.isEmpty(textTitle.getText())
|| TextUtils.isEmpty(textBody.getText()){
Log.e("NotificationClick", "A TextView was empty or null");
return;
}
String ticker = textTicker.getText().toString();
String title = textTitle.getText().toString();
String body = textBody.getText().toString();
notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher);
.setTicker(ticker);
.setWhen(System.currentTimeMillis());
.setContentTitle(title);
.setContentText(body);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
handler.postDelayed(runnable, 20 * 1000); //twenty seconds delay
}
private Runnable runnable = new Runnable() {
@Override
public void run() {
NotificationManager nm =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
};
答案 1 :(得分:-1)
请注意,处理程序的使用始终是精确的,因为在深度睡眠中花费的时间会给执行带来额外的延迟"。因此,如果你想要一个精确的时间(比如游戏能量棒),你应该选择其他东西而不是处理程序。