【问题标题】:Issue loading next activity问题加载下一个活动
【发布时间】:2014-12-05 08:27:05
【问题描述】:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.initial_layout);
// progress bar
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
@Override
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
pbHandler.post(new Runnable() {
@Override
public void run() {
pb.setProgress(progressStatus);
}
});
try {
Thread.sleep(70);
}catch (Exception e) {
e.printStackTrace();
}
}
if (pb.getProgress() >= 95) {
Intent i1 = new Intent(initialActivity.this,startingActivity.class);
startActivity(i1);
}
}
}).start();
}
我的目标是在进度条完成加载而不触发任何其他事件时自动加载下一个活动,但我似乎无法做到这一点。我猜线程有问题,我是初学者。任何帮助表示赞赏。
【问题讨论】:
标签:
android
android-intent
android-activity
progress-bar
progress
【解决方案1】:
You have to start the activity from the main thread. Consider executing the runnable from a handler. ` Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
pbHandler.post(new Runnable() {
@Override
public void run() {
pb.setProgress(progressStatus);
}
});
try {
Thread.sleep(70);
}catch (Exception e) {
e.printStackTrace();
}
}
if (pb.getProgress() >= 95) {
Intent i1 = new Intent(initialActivity.this,startingActivity.class);
startActivity(i1);
}
}
},1000);
return;`
【解决方案2】:
定义自定义接口,让您在进度完成时回调:
public interface OnProgressFinishListener{
public void onProgressFinish();
}
使用AsyncTask更新进度:
public void startProgress(final OnProgressFinishListener onProgressFinishListener){
new AsyncTask<Void,Integer,Integer>(){
@Override
protected Integer doInBackground(Void... params) {
while (progressStatus < 100) {
progressStatus += 1;
publishProgress(progressStatus);
try {
Thread.sleep(70);
}catch (Exception e) {
e.printStackTrace();
}
}
return progressStatus;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pb.setProgress(values[0]);
}
@Override
protected void onPostExecute(Integer progress) {
super.onPostExecute(progress);
if(progress==100){
onProgressFinishListener.onProgressFinish();
}
}
}.execute();
}
如何实现自定义接口:
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
startProgress(new OnProgressFinishListener() {
@Override
public void onProgressFinish() {
pb.setVisibility(View.GONE);
Toast.makeText(MainActivity.this,"Progress Finish",Toast.LENGTH_SHORT).show();
}
});
【解决方案3】:
if (pb.getProgress() >= 95) {
Intent i1 = new Intent(initialActivity.this,startingActivity.class);
startActivity(i1);
}
上面的代码不正确
if (pb.getProgress() >= 95) {
Intent i1 = new Intent(context,startingActivity.class);
startActivity(i1);
}
将当前activity的上下文存储在activity的成员变量中;
public Context context = getApplicationContext();
更好的解决方案是使用 AsynTask
例子
http://programmerguru.com/android-tutorial/android-asynctask-example/