2015-04-17 106 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更多的東西。