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();
}
我的目标是在进度条完成加载时自动加载下一个活动,而不会触发任何其他事件,但我似乎无法做到这一点。我觉得线程有些不对劲,我是个傻瓜。任何帮助表示赞赏。
答案 0 :(得分:2)
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;`
答案 1 :(得分:0)
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);
}
将上下文存储在活动成员变量中的当前活动中;
public Context context = getApplicationContext();
更好的解决方案是使用AsynTask
示例
http://programmerguru.com/android-tutorial/android-asynctask-example/
答案 2 :(得分:0)
定义自定义界面,让您在完成进度时回调:
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();
}
});