gpt4 book ai didi

android - 在不访问线程对象的情况下杀死线程

转载 作者:行者123 更新时间:2023-11-29 21:13:18 25 4
gpt4 key购买 nike

我有一个线程,我想让用户在单击进度通知时终止该线程。

我的通知工作正常,但在我的 BroadcastReciever 中我无法设法终止线程。

我不能使用 thread.interupt(),因为我无权访问线程对象。这也意味着我不能使用公共(public) bool 值来终止线程。

我还尝试将进程 ID 作为额外传递,并使用 Process.killProcess(pid) 终止它,但这有相当不幸的副作用,即终止我的 UI 线程和我的任何其他线程可能正在运行。

最后,我尝试使用线程 ID,但文档中没有提到使用它来终止线程。

简而言之,如何使用可以作为附加值传递的原始数据类型终止我的线程?

最佳答案

您正在以错误的方式看待它。

如果您有一个线程正在运行并且通知栏上有一个通知,我会假设您有一个正在运行的服务,并且该服务知道该线程并且确实有一个对它的引用。这样,您的通知的 PendinIntent 不应简单地触发 BroadcastReceiver,而是触发具有指示服务应取消线程的 Intent extra 的相同服务。

假设您的服务:

public MyService extend Service{

private Runnable myThread = new Runnable{
@Override
public void run(){
// ... here you're doing the job on the different thread
}
};
}

类似的东西:

Intent i = new Intent(this, MyService.class);
i.putExtra("cancel", true);
PendingIntent pi = PendingIntent.getService(// put here the intent)

然后,每当单击通知时,您的具有线程的服务将从 onStartCommand 执行,您需要做的就是:

cancel = getIntent.getBooleanExtra("cancel", false);

然后在线程中,您必须像这样从服务中检查 boolean cancel:

public MyService extend Service{

boolean cancel = false;

private Runnable myThread = new Runnable{
@Override
public void run(){
// ... here you're doing the job on the different thread

if(cancel)
return;
}
};
}

关于android - 在不访问线程对象的情况下杀死线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22131715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com