我从Application
类开始,在onCreate
中,一个后台线程(AsyncTask
),这会占用一些时间(15到70秒之间)。
在一项活动中,我只有在Application
onCreate()
方法中启动该任务时才需要进行一些操作。
我的解决方案是:
Application
class AsyncTask
onPostExecute
方法中,我更新了listener
boolean
正在进行或已被终止,我还有一个asyncTask
变量可以从poutside知道MyActivity
class listener
asyncTask
正在进行中,我设置了listener
,当onCommandEnded
完成后,AsyncTask
会通知我,并执行操作我不确定这是否是正确的方法......
import android.app.Application;
import android.content.Context;
import android.os.AsyncTask;
public class MyApplicationClass extends Application {
protected static MyApplicationClass instance;
public static MyApplicationClass getInstance() {
return instance;
}
private ApplicationListener listener;
public void setListener(ApplicationListener listener) {
this.listener = listener;
}
public static interface ApplicationListener {
void onCommandEnded();
}
private boolean isInProgress;
@Override
public void onCreate() {
super.onCreate();
instance = this;
CommandAsyncTask copyFfmpeg = new CommandAsyncTask();
copyFfmpeg.execute();
}
private class CommandAsyncTask extends AsyncTask<Void, Void, Double> {
@Override
protected void onPreExecute() {
super.onPreExecute();
isInProgress = true;
}
@Override
protected Double doInBackground(Void... params) {
//do some time consuming operations here
return null;
}
@Override
protected void onPostExecute(Double aDouble) {
if (listener != null) {
listener.onCommandEnded();
}
isInProgress = false;
super.onPostExecute(aDouble);
}
}
public boolean isInProgress() {
return isInProgress;
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyActivity extends Activity implements MyApplicationClass.ApplicationListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MyApplicationClass.getInstance().isInProgress()) {
MyApplicationClass.getInstance().setListener(MyActivity.this);
} else {
//start new asynctask
}
}
});
}
@Override
public void onCommandEnded() {
//start here new asynctask
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
</LinearLayout>