2017-06-06 81 views
1

你好,我是Android開發的新手,努力向我自己學習! 我只是想在我的應用程序的Java線程中更新我的通知(我只是在學習和好奇我該怎麼做)。持續更新通知


我有一個活動,一個簡單的線程來遞增整數值。然後,只要Integer值遞增,我只想在我的Notification中顯示它! 我的代碼:

public class MainActivity extends Activity{ 
     private final String LOG_KEY = this.getClass().getSimpleName(); 
     private int c = 0; 
     private boolean flag = true; 
     private NotificationCompat.Builder builder; 
     private NotificationManager notificationManager; 

     @Override 
     protected void onCreate(Bundle savedInstanceState){ 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

      builder = new NotificationCompat.Builder(MainActivity.this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setAutoCancel(false); 

      builder.setOngoing(true); 

      notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 

      Thread t = new Thread(new MyThread()); 
      t.start(); 
     }//OnCreate ends 

     @Override 
     protected void onStop() { 
      super.onStop(); 
      flag = false; 
     }//stop ends 

     @Override 
     protected void onDestroy() { 
      super.onDestroy(); 
      flag = false; 
     }//destroy ends 

     private class MyThread implements Runnable { 
      @Override 
      public void run() { 
       while (flag) { 
        c+=1; 
        showNotification(Integer.toString(c) + " Counts"); 
       }//while ends 
      }//run ends 

      private void showNotification(String msg) { 
       try { 
        //set the notification 
        builder.setContentText(msg); 
        notificationManager.notify(0, builder.build()); 
       } catch (Exception exp) { 
        Log.e("xmn", exp.toString()); 
       }//try catch ends 
      }//showNotification ends 

     }//private class ends 
    }//MainActivity class ends here 

當從我的代碼,該通知顯示,更新值!但問題是,它突然凍結了設備和應用程序!

我只是想幫助我做錯了,因爲我是一個新手,並將它學習到我自己。任何幫助和想法將不勝感激!


感謝

回答

0

你不應該繼續創造一個通知,然後以最快的速度從一個線程可以更新它。它並不是爲此而設計的。

我能想到的最接近的事將滿足您的使用案例是使用通知顯示進度。請參閱此鏈接:

Displaying Progress in a Notification

你可能想要把某種速率限制在你的線程,除非你想讓你的數很快達到非常高的數字。也許讓線程在更新之間休眠一秒鐘。

0

問題是,您產生的通知多於設備可以消耗的。

對於你的目標(剛學的),你可以通知之間添加一些停頓這樣的:

private void showNotification(String msg) { 
    try { 
     //set the notification 
     Thread.sleep(1000); //set the pause 

     builder.setContentText(msg); 
     notificationManager.notify(0, builder.build()); 
    } catch (Exception exp) { 
     Log.e("xmn", exp.toString()); 
    }//try catch ends 
}//showNotification ends 
+0

這僅僅是一個很酷的想法戴的帽子 –