gpt4 book ai didi

android - 线程不工作。应用程序意外关闭。

转载 作者:行者123 更新时间:2023-11-29 21:49:11 24 4
gpt4 key购买 nike

我试图在按下刷新按钮时在我的程序中显示进度对话框,但应用程序关闭未扩展,调试器中出现错误,即创建的 ui 层次结构的线程只能触摸它。

    public class MainActivity extends Activity {
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.refreshView();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public void refreshView(){
ImageView img = (ImageView) findViewById(R.id.imageView1);
Bitmap bm = null;
InputStream is = null;
BufferedInputStream bis = null;
try
{
URLConnection conn = new URL("http://technomoot.edu.pk/$Common/Image/Content/ciit_logo.jpg").openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream(is, 8192);
bm = BitmapFactory.decodeStream(bis);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
if (bis != null)
{
try
{
bis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
img.setImageBitmap(bm);
}

public void onRefresh(View view) {

final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Loading the image of the Day");
Thread th = new Thread(){
public void run(){
refreshView();
handler.post(new Runnable(){
public void run(){
dialog.dismiss();
}
}
);
}

};th.start();
}

}

最佳答案

您不能使用工作程序 Thread 中的 UI 进行操作!它是被禁止!如果你想更新 UI 只需使用

  • runOnUiThread()
  • AsyncTask

所以试试这样:

runOnUiThread(new Runnable() {

@Override
public void run() {
// do your work.

}
});

AsyncTask 更复杂,也是泛型类型,提供了一些好处,例如类型控制等。您可以在此处查看示例:

关于android - 线程不工作。应用程序意外关闭。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com