如何在另一个Android线程结束时启动Android线程

时间:2015-03-04 23:47:05

标签: java android multithreading

我希望这个android程序在写入文件之前有10秒倒计时,然后读取并设置为MainActivity上的文本。我希望mCounterThread在mFileThread启动之前完成其任务。由于onPause()和onResume()可能会延长所需的时间,因此我无法在固定时间内执行.sleep(毫秒)。我试过thread.join(),但这似乎不起作用。为什么?我可以使用另一个通知/等待吗?谢谢

public class MainActivity extends Activity {
private TextView mText;
private EditText mUserInput;
private CounterThread mCounterThread;
private MakingFileThread mFileThread;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mText = (TextView)findViewById(R.id.text);
    mUserInput = (EditText)findViewById(R.id.userInput);
    mCounterThread = new CounterThread();
}

@Override
public synchronized void onPause(){
    super.onPause();
    mCounterThread.onPause();
}

@Override
public synchronized void onResume(){
    super.onResume();
    mCounterThread.onResume();
}

public void startCounterThread(){
    mCounterThread.start();
}

public void startMakingFileThread(String s1,String s2){
    mFileThread = new MakingFileThread(s1,s2);
    mFileThread.start();
}

public void button_handler(View v){
    String val = mUserInput.getText().toString();
    startCounterThread();
    String file = "myfile.txt";
    startMakingFileThread(val, file);//I want this to start only 
    //once mCounterThread has finished its countdown.
   }

public void updateSeconds(final long seconds){
    Runnable UIdoWork = new Runnable(){
        public void run(){
            String time = String.valueOf(seconds);
            mText.setText("Your file will open in " + time + " seconds");
        }
    };
    runOnUiThread(UIdoWork);
}


public void updateWriteFile(final String userText){
    Runnable UIdoWork = new Runnable(){
        public void run(){
            mText.setText(userText);
        }
    };
    runOnUiThread(UIdoWork);
}

private class CounterThread extends Thread{
    private int count = 10;
    private final Object lock = new Object();
    private volatile boolean isRunning = true;

    public void onResume(){
        if(!isRunning){
            isRunning = true;
        }
        synchronized (lock){
            lock.notify();
        }
    }

    public void onPause(){
        isRunning = false;
    }


    @Override
    public synchronized void run(){
        while(count != 0){
            synchronized (lock){
                if(!isRunning)try{
                    lock.wait();
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }

            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            updateSeconds(count--);
         }

    }
}

private class MakingFileThread extends Thread{
    private String userInput;
    private String fileName;

    public MakingFileThread(String s1,String s2){
        userInput = s1;
        fileName = s2;
    }

    @Override
    public void run(){
        try{
            sleep(20000);//right now I have this thread
            //wait 20 seconds before it starts
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream outputStream =      openFileOutput(fileName,MODE_PRIVATE);
            BufferedWriter writer = new BufferedWriter((new OutputStreamWriter(outputStream,"UTF-8")));
            writer.write(userInput);
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        try {
            FileInputStream fis = openFileInput( fileName );
            BufferedReader reader = new BufferedReader((new InputStreamReader(fis,"UTF-8")));
            String ans = reader.readLine();
            updateWriteFile(ans);
            reader.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

}

1 个答案:

答案 0 :(得分:0)

AsyncTask#postExecute()方法是否适合您的需求?如android文档中所述:

  

AsyncTask可以正确,轻松地使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

     

...

     

异步任务由在后台线程上运行的计算定义,其结果在UI线程上发布。异步任务由3种泛型类型定义,称为Params,Progress和Result,以及4个步骤,称为onPreExecute,doInBackground,onProgressUpdate和onPostExecute。

在Android中还有一个用于倒计时的东西,不要重新发明轮子。请参阅CountDownTimer

的文档

您可以在AsyncTask和postExecute回调中执行文件处理,执行其他所需的操作。