线程不会在 onPause 中停止

发布于 2024-12-21 21:56:24 字数 2445 浏览 1 评论 0原文

我试图在 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();
        }

I'm trying to stop my thread in my onPause() but the thread still runs and gets the notification that is sent when the thread expires. It seems I have everything set right... My notifcation works fine and comes up after the 8000 sleep.. but if the user leaves/onPause() before then the notification will still pop.

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();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪落纷纷 2024-12-28 21:56:24

Firstly:您希望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 可能是一个更好的主意,或者使用 View#postDelayed(Runnable, long)Runnable 发布到布局中的视图)

Firstly: Do you want the code in the finally statement to always execute? Because, as written, you're not going to be able to exit the thread without updating your notification.

If thats ok, just call timer.interrupt(), which will trigger your InterruptedException handler & then call your finally block - if you're averse to interrupting threads and really feel attached to your Thread you can always use a latch to release it.

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.
    }

(FYI: An AsyncTask is probably a better idea or posting a Runnable to a View in your layout using View#postDelayed(Runnable, long) )

回忆躺在深渊里 2024-12-28 21:56:24

只是出于好奇,你怎么知道 onPause() 实际上被调用了?

使用 Toast 或 Log 找出您的应用程序进入 onPause() 状态

Just out of curiosity, how do you know that onPause() is actually called?

Use Toast or Log to find out, that your app enters the onPause() state

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文