標籤:android style blog http io os ar sp 2014
============問題描述============
最近做一個計算量比較大的應用,程式在計算的時候應用會卡住並且黑屏但並不會報錯,計算完成後程式會繼續運行,請問怎麼在計算過程中加一個載入條讓應用不會黑屏呢...?
============解決方案1============
是在顯示計算結果前,提示使用者“正在計算...”這樣的訊息嗎?然後計算出結果,提示消失嗎?這樣的話你可以寫一個progressDialog對話方塊,選擇圓形的那個風格...
============解決方案2============
把你的計算代碼交給服務或者線程處理,結果用廣播返回,開始處理時UI顯示提示資訊,UI監聽結果,處理完後更新UI介面。
============解決方案3============
應用線程進行計算, 計算完成了更新介面
============解決方案4============
瞭解下非同步線程Asynctask的用法,應該能幫到你
============解決方案5============
計算部分,放到線程裡去,另外,UI線程顯示progressDialog,在計算完後,線程通過handler通知關閉progressDialog
============解決方案6============
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.picture);
button=(Button)findViewById(R.id.button);
dialog=new ProgressDialog(this);
dialog.setTitle("提示");
dialog.setMessage("圖片下載中");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(false);
}
public class myTask extends AsyncTask<String,Integer,Bitmap>{
//表示任務操作之前的操作
@Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
dialog.setProgress(values[0]);
}
//主要執行耗時操作
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
InputStream inputStream=null;
Bitmap bitmap=null;
try {
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(params[0]);
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
inputStream=httpResponse.getEntity().getContent();
long file_length=httpResponse.getEntity().getContentLength();
int len=0;
byte[] data=new byte[1024];
int total_length=0;
while((len=inputStream.read(data))!=-1){
total_length+=len;
int value=(int)((total_length/(float)file_length)*100);
publishProgress(value);
outputStream.write(data,0,len);
}
byte[]result=outputStream.toByteArray();
bitmap=BitmapFactory.decodeByteArray(result, 0, result.length);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return bitmap;
}
//跟新UI介面
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
imageView.setImageBitmap(result);
dialog.dismiss();
}
}
我這個是橫向的,你可以選擇圓形的,而且我這個可以根據網路下載的,顯示進度。你可以根據自己的需要改一下,把你的計算操作放到doInBackground裡面就可以了。
android圓形載入條問題