我的启动画面同步了我的应用:
当我使用时:
sd.execute("init_sync", null).get();
我的徽标(以xml定义)消失。如果我退出.get(),它就会出现。
这是我的代码:
public class SplashScreen extends Activity {
private Context ctx = null;
private Usuario mUser = null;
SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ctx = this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
new Handler().post(new Runnable() {
@Override
public void run() {
// Check if user exists
Gson gson = new Gson();
String jsonUser = prefs.getString("usuario", "");
mUser = gson.fromJson(jsonUser, Usuario.class);
if (NetworkUtils.isOnline(ctx)) {
if (mUser != null) {
SyncData sd = new SyncData(ctx);
try {
sd.execute("init_sync", null).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
}
} else {
if (mUser != null) {
Intent i = new Intent(SplashScreen.this, DashBoard.class);
startActivity(i);
} else {
Toast.makeText(ctx, "Necesita Internet para loguearse", Toast.LENGTH_LONG).show();
finish();
}
}
}
});
}
}
我有几个asyncTask用于上传图片,并将MySQL数据库与我的SQLite数据库同步。所以,我需要等到所有进程结束才能知道是否有错误。
问题是我把它放在一个线程中,所以它不会影响UI。我哪里错了?
答案 0 :(得分:1)
使用get()
时,会导致UI线程等待。不要使用get()
。您需要覆盖onPostExecute
中的AsyncTask
方法。
private Boolean task1Finished = false;
private Boolean task2Finished = false;
private Boolean task3Finished = false;
//...
SyncData sd1 = new SyncData(ctx) {
@Override
protected void onPostExecute(Object result) {
task1Finished = true;
goToNextActivity();
}
};
SyncData sd2 = new SyncData(ctx) {
@Override
protected void onPostExecute(Object result) {
task2Finished = true;
goToNextActivity();
}
};
SyncData sd3 = new SyncData(ctx) {
@Override
protected void onPostExecute(Object result) {
task3Finished = true;
goToNextActivity();
}
};
try {
sd1.execute();
sd2.execute();
sd3.execute();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
//...
private void goToNextActivity() {
if (task1Finished && task2Finished && task3Finished)
// all tasks complete
}
答案 1 :(得分:0)
就像@ashishduh所说,我在UI线程中。所以我改变了:
new Handler().post(new Runnable() {
@Override
public void run() {
....
}
}
通过
Runnable sync = new Runnable() {
@Override
public void run() {
....
}
};
Thread t = new Thread(sync);
t.start();
它解决了我的问题!