Android activity 在按下后退按钮之前无响应

Android activity unresponsive until back button is pressed

下面是我 activity 的 oncreate。我的问题是,当 activity 启动时,它完全没有响应,直到我按下后退按钮。一旦我按下后退按钮,它就会完美运行。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_packs);
    count = 0;

    Bundle extras = getIntent().getExtras();
    if(extras != null || !equals("")){
        name = extras.getString("name");
    }
    else{name="PackActivity";}


    //getActionBar().setTitle(name);  
    ActionBar actionBar = getActionBar();
    //actionBar.setBackgroundDrawable(R.drawable.navigation_bar_colour_image);
    //actionBar.setHomeButtonEnabled(true);
    actionBar.setTitle(name);

    actionBar.setDisplayHomeAsUpEnabled(false);
    //actionBar.hide();
    database = new DataObjectDataSource(this.getApplicationContext());
    //load all the packs from the DB
    packs = loadPacks();
    //make the request for GetPacks
    sortArrayById();

    if(isOnline(this)) {
        HTTPRequest.getHTTPRequest(HTTPRequest.getPacksURL, this);
    }
    else{
        dialog("No internet connection available","their is limited functionality available in offline mode",1);
    }


    gridView = (GridView) findViewById(R.id.packGrid);

    adapter = new PackGridAdapter(this, getApplicationContext(), packs);
    gridView.setAdapter(adapter);
    gridView.setOnItemClickListener(this);

    System.out.println(" pack_ids ");
}

我添加了对话框功能,因为在关闭后出现无响应。

public boolean dialog(String mes,String message,int type){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // Add the buttons
    if(type==2){
        builder.setMessage(message)
        .setTitle(mes);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                   }
               });
    }
    // Create the AlertDialog
    final AlertDialog dialog = builder.create();
    dialog.show();
    if(type==2){
        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            public void run() {
                dialog.dismiss();
                // when the task active then close the dialog
                t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
            }
        }, 5000);

    }
    return true;
}

2 件事:

首先确认您的 ActionBar 代码正常工作(评论 actionbar 部分以确保它不是这里的罪魁祸首)以查看 activity 是否响应

如果第一个不起作用,甚至在评论后 ActionBar activity 也没有反应.. 那么

第 2 条评论这些行:

if(isOnline(this)) {
    HTTPRequest.getHTTPRequest(HTTPRequest.getPacksURL, this);
}
else{
    dialog("No internet connection available","their is limited functionality available in offline mode",1);
}

我怀疑您在 UI 线程上进行了一些网络操作,这可能是 Activity 没有响应的原因,或者它一定与 dialog 有关你正在使用的方法。如果您显示该方法代码,它可能会导致进一步诊断。