2011-10-25 49 views
4

的消息,我發現如何從子類訪問上下文的一些信息,也有一些信息關於「吐司」通過的TimerTask

runOnUiThread(new Runnable() { 
    public void run() { 
    // Do something 
    } 
}); 

但在我的情況下,這是行不通的。該應用程序仍在運行,但該活動可能已被破壞。第一個(主要)活動是創建TimerTask的父活動。我的代碼:

TimerTask tt = new TimerTask() { 
    @Override 
    public void run() { 
    // do something (cut) 

    // and at the end show info 
    getParent().runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
     Toast.makeText(getParent(), 
        getResources().getString(R.string.st_toast_msg_stopped), 
        Toast.LENGTH_LONG).show(); 
     } 
    }); 
    } 
}; 
curTimer.schedule(tt, millisecondsUntilStop); 

日誌中沒有錯誤/異常。但敬酒信息未顯示。 :-(

現在我不知道我可以做別的/嘗試,我希望你們有人能幫助我

PS:也許我使用了錯誤的情況下,但我想也有一些其他方面怎麼樣?當前活動的背景下,ApplicationContext,...。

回答

2

那麼你在這裏使用的是錯誤的背景是getParent()。請使用getParent()嘗試使用這樣的current_Activity.this

TimerTask tt = new TimerTask() { 
    @Override 
    public void run() { 
    // do something (cut) 

    // and at the end show info 
    Activity_name.this.runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
     Toast.makeText(Activity_name.this, 
        getResources().getString(R.string.st_toast_msg_stopped), 
        Toast.LENGTH_LONG).show(); 
     } 
    }); 
    } 
}; 
+0

這工作,謝謝! – nauni77

0

而不是使用一個TimerTask,何不用戶AlarmManager並設置PendingIntent仍然發射廣播呢?當你火了廣播和抓住它你自己的BroadcastReciever,你將在你的BroadcastReciever中有上下文顯示你的吐司。下面是一個快速的高級示例。

你在哪裏都是在爲你的活動設置你的TimerTask,而是執行此操作:

AlarmManager alarmManager = (AlarmManager)Context.getSystemService(Context.ALARM_SERVICE); 
Intent broadcastIntent = new Intent("yourBroadcastAction"); 
PendingIntent pendingIntent = PendingIntenet.getBroadcast(this, 0, broadcastIntent, 0); 
alarmManager.set(AlarmManager.ELAPSED_REALTIME, millisecondsUntilStop, broadcastIntent); 

然後,只需創建一個具有過濾器爲yourBroadcastAction,並在onRecieve()方法BroadcastReciever做你的麪包,像這樣:

public void onRecieve(Context context, Intent intent){ 
    Toast.makeText(context, 
       getResources().getString(R.string.st_toast_msg_stopped), 
       Toast.LENGTH_LONG).show(); 
} 
+0

感謝您的提示。我相信這應該也可以!非常感謝! – nauni77