2015-04-17 108 views
0

我想延迟通知构建到1分钟,我该怎么做?我试图插入一个处理程序和postDelaying它,但我得到了多个错误。延迟通知构建(Android)

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

你得到了什么样的错误? – Blackbelt

+0

这是当我试图使用处理程序,但我从原始代码中删除它。 错误:(59,33)错误:Handler是抽象的;无法实例化 错误:(60,16)错误:找不到符号方法postDelayed(,int) – Oyee

+1

您确定导入了正确的'Handler'。 java.util.logging包中有一个抽象处理程序。你想要一个'android.os' – Knossos

回答

1

一定要导入正确的处理程序:

import android.os.Handler;

创建的处理程序和运行的。可运行的代码将会在延迟之后执行。

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()); 
    } 
}; 
+0

这是错误的处理程序类,但我不明白如何设置onClick现在? – Oyee

+0

yourview.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ //做点什么 } }); –

+0

@Oyee见编辑,解释如何使用onClick –

0

只要注意,使用该处理器的is'nt总是准确的,因为“时间深睡眠中度过将额外的延迟添加到执行”。所以如果你想要一个精确的时间(比如一个游戏能量棒),你应该选择一个比Handler更多的东西。