你好,我是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
當從我的代碼,該通知顯示,更新值!但問題是,它突然凍結了設備和應用程序!
我只是想幫助我做錯了,因爲我是一個新手,並將它學習到我自己。任何幫助和想法將不勝感激!
感謝
這僅僅是一個很酷的想法戴的帽子 –