我正在尝试在我的onPause()中停止我的线程,但该线程仍然运行并获取线程到期时发送的通知。似乎我已经把一切都设置得正确...我的通知工作正常并在8000睡眠后出现..但如果用户离开/ onPause()之前通知仍然会弹出。
private static final int MY_NOTIFICATION_ID=1;
private NotificationManager notificationManager;
private Notification myNotification;
Thread timer;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.expire);
timer = new Thread(){
public void run(){
try{
sleep(8000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
myNotification = new Notification(R.drawable.missedcall,
"Exired",
System.currentTimeMillis());
Context context = getApplicationContext();
String notificationTitle = "Time Expired";
String notificationText = "Try next time";
Intent myIntent = new Intent();
PendingIntent pendingIntent
= PendingIntent.getActivity(CallScreen.this,
0, myIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
myNotification.defaults |= Notification.DEFAULT_SOUND;
myNotification.flags |= Notification.FLAG_AUTO_CANCEL;
myNotification.setLatestEventInfo(context,
notificationTitle,
notificationText,
pendingIntent);
notificationManager.notify(MY_NOTIFICATION_ID, myNotification);
finish();
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
timer.stop();
finish();
}
答案 0 :(得分:0)
首先:您是否希望finally
语句中的代码始终执行?因为,如上所述,您无法在不更新通知的情况下退出该线程。
如果可以,只需调用timer.interrupt()
,这将触发您的InterruptedException处理程序&然后调用你的finally
块 - 如果你反对中断线程并且真的感觉附加你的线程,你总是可以使用一个锁存器来释放它。
public class SomeDamnedActivity extends Activity {
// ... misc junk ...
private CountDownLatch mLatch;
private Thread mThread;
protected void onCreate(Bundle savedInstanceState) {
mLatch = new CountDownLatch(1);
mThread = new Thread() {
public void run() {
try {
mLatch.await(8, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Log.w(TAG, "Interrupted waiting for latch to release", e);
} finally {
// Stuff goes here that you want to execute.
}
}
};
}
protected void onPause() {
// ...
mLatch.countDown(); // This will release the latch "prematurely" calling your finally-statement.
}
(仅供参考:AsyncTask可能是一个更好的主意或使用Runnable
向您的布局中的视图发布View#postDelayed(Runnable, long)
)
答案 1 :(得分:-1)
出于好奇,你怎么知道onPause()实际上被调用了?
使用Toast或Log查找您的应用进入onPause()状态