public class Activity1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.B);
final ProgressBar p=(ProgressBar) findViewById(R.id.pr);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
p.setVisibility(4);
Thread t=new Thread();
try{
t.sleep(5000);
}
catch(Exception e){}
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
});
}}
答案 0 :(得分:5)
为此更改OnClickListener。这不会像你一样阻止你的主线程(这解释了为什么你的应用程序冻结了5秒):
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<Integer, Long, Boolean>()
{
ProgressDialog pd;
@Override
protected Boolean doInBackground(Integer... params)
{
pd = new ProgressDialog(Activity1.this);
pd.setTitle("Loading Activity");
pd.setMessage("Please Wait ...");
pd.setMax(params[0]);
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
publishProgress(0L);
long start = System.currentTimeMillis();
long waitTime = params[0] * 1000;
try
{
while (System.currentTimeMillis() - start < waitTime)
{
Thread.sleep(500);
publishProgress(System.currentTimeMillis() - start);
}
}
catch (Exception e)
{
return false;
}
return true;
}
@Override
protected void onProgressUpdate(Long... values)
{
if (values[0] == 0)
{
pd.show();
}
else
{
pd.setProgress((int) (values[0] / 1000));
}
}
@Override
protected void onPostExecute(Boolean result)
{
pd.dismiss();
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
}.execute(5);
});
答案 1 :(得分:4)
你最好为此目的使用AsyncTask。在你的活动中使用这样的线程是不正确的,可能导致一些失败。查看关于AsyncTask的文档。
http://developer.android.com/resources/articles/painless-threading.html
答案 2 :(得分:4)
不要使用Thread.sleep() - 它是万恶之源。相反,请使用Handler
及其postDelayed( Runnable, time )
- 方法,如下所示:
public class Activity1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.B);
final ProgressBar p=(ProgressBar) findViewById(R.id.pr);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
p.setVisibility(4);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
}, 5000);
}
});
}
答案 3 :(得分:3)
首先在上面的代码中,你需要使用它启动Thread。
t.start();
你也可以尝试下面的代码,
new Thread ( new Runnable() { public void run() { // Place your Intent Code here } }.start();