我试图找出如何知道线程何时完成。
public void movetoKnox(View view) throws Exception
{
countp = 0;
Runnable r = new Runnable() {
@Override
public void run() {
count = movefileList.size();//4
count2 = multiFile.size();//2
for (int i =0; i<count; i++)
{
for( int j=0; j<count2;j++)
{
if(movefileList.get(i).equals(multiFile.get(j)))
{
File temp = new File(multiFile.get(j));
try{
//copyFile(temp,chamberLocation);
copyFileOrDirectory(multiFile.get(j),chamberLocations);
}catch (Exception e)
{
Log.e(TAG,"Exception Alex: "+e);
// Toast.makeText(moveKnox.this, "Exception: "+e,Toast.LENGTH_SHORT).show();
}
}
}
}
}
};
Thread t = new Thread(r);
t.start();
目前这个线程批量进行数据传输。它可以从几mb到gb。我希望能够分辨数据传输何时完成,并在后台显示吐司。
我认为创建一个新线程并在其中调用t.join()会起作用,但它只会崩溃,我应该以什么方式处理它。
答案 0 :(得分:1)
导入
import android.os.Handler
在我添加的主线程中。
Handler handler = new Handler()
{
@override
public void handleMessage(Message msg)
{
Toast.makeText(getContext,"TRANSFER COMPLETE",TOAST.LENGTH_SHORT).show();
}
};
public void movetoKnox(View view) throws Exception
{
countp = 0;
Runnable r = new Runnable() {
@Override
public void run() {
count = movefileList.size();//4
count2 = multiFile.size();//2
for (int i =0; i<count; i++)
{
for( int j=0; j<count2;j++)
{
if(movefileList.get(i).equals(multiFile.get(j)))
{
File temp = new File(multiFile.get(j));
try{
//copyFile(temp,chamberLocation);
copyFileOrDirectory(multiFile.get(j),chamberLocations);
}catch (Exception e)
{
Log.e(TAG,"Exception Alex: "+e);
// Toast.makeText(moveKnox.this, "Exception: "+e,Toast.LENGTH_SHORT).show();
}
}
}
}
**handler.sendEmptyMessage(0);**
}
};
Thread t = new Thread(r);
t.start();
答案 1 :(得分:0)
您需要的可能就是这么简单:
final MyClass self = this;
Runnable r = new Runnable() {
@Override
public void run() {
// ** some code that takes forever **
self.doADance(); // this is your toast animation or whatever you want
}
};
这里发生的关键事情:
final
保留对当前对象的引用,以便我们稍后在Runnable
doADance
。