我正在开发一个 android 应用程序并尝试处理线程而不真正了解它们......(是的,我有点愚蠢,我知道)
我将尝试正确且快速地解释它。
在我的 Activity 的 onCreate 方法中,我正在调用 AlertDialog 以使用户选择从 Internet 加载数据或使用先前存储在数据库中的数据直接访问应用程序。
为此,在 onCreate 中,我调用我的方法来引发 AlertDialog,肯定按钮应该启动工作线程下载,否定按钮应该调用 Intent 移动到下一个 Activity 。到目前为止,我得到了这个:
wait()
在任何地方,我的 AlertDialog 都会出现,但线程仍然开始 wait()
在我的线程的第一行,我必须将它声明为静态,以便从我的 AlertDialog 的监听器访问它,并且能够 notify()
它或 interrupt()
,我收到错误:object not locked by thread before wait()
. worker = new Thread(new Runnable() {
public void run() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
[我的运行方法的其余部分]
private void miseAJourDesDonnes() {
confirmInscrip = new AlertDialog.Builder(this).setMessage(
"Voulez-vous mettre à jour l'intégralité des données de l'application? (Connexion internet requise").setPositiveButton("Mettre à jour",
okListener).setNegativeButton("Continuer sans", nonListener);
confirmInscrip.create();
confirmInscrip.show();
}
OnClickListener okListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(AccueilSplash.this, "Mise à jour en cours", Toast.LENGTH_SHORT).show();
worker.notify();
return;
}
};
OnClickListener nonListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(AccueilSplash.this, "Accès direct à l'application", Toast.LENGTH_SHORT).show();
worker.interrupt();
Intent entre = new Intent(AccueilSplash.this, Androt.class);
startActivity(entre);
}
};
worker 是我的 Thread 实例(bbackground 之一)
我只是愚蠢还是有我没有掌握的微妙之处?
感谢您的任何回答...
最佳答案
下面是对 wait() 和 notify() 工作原理的快速解释,但我是否建议您不要创建工作线程,除非用户单击确定?如果他们想停止下载,您可能仍想稍后取消该线程,但在您知道是否要使用它之前创建线程似乎不是最好的方法。
为了调用wait()
, notify(),
或 notifyAll()
在一个对象上,您必须首先拥有您希望调用该方法的对象的监视器,所以在您的情况下,在可运行的情况下,您需要这样做:
Runnable runnable = new Runnable() {
public void run() {
// wait(); This call wouldn't work
syncronized (this) {
wait(); // This call will work
}
}
};
要通知该可运行文件,您还必须拥有监视器
// runnable.notifyAll(); this call will not work
syncronized (runnable) {
runnable.notifyAll(); // this call will work
}
有关 Java 中的线程和并发的更多信息,我建议 Java Concurrency in Practice
Android中可能有一些我不知道的用于后台任务的内置框架,但是使用纯Java最简单的方法似乎是这样的:
私有(private)线程下载线程;
OnClickListener okListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Runnable download = new Runnable() {
public void run() {
// Create your input streams and such
boolean downloadComplete = false;
while(!downloadComplete && !Thread.currentThread().isInterruped()) {
// Do some downloading
}
if (!Thread.currentThread().isInterruped()) {
// Alert user of success.
}
}
};
downloadThread = new Thread(download);
downloadThread.start();
}
};
OnClickListener cancelListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downloadThread.interrupt();
}
};
关于java - 访问线程以从另一个方法通知它(Android 应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392297/