private Thread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.e(TAG, "main OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = new DBHandler(this);
currentDate = Calendar.getInstance();
formatter= new SimpleDateFormat("yyyy-MM-dd");
thread = new Thread(){
@Override
public void run(){
try {
synchronized(this){
wait(120000);
Log.e(TAG, "thread");
}
}
catch(InterruptedException ex){
Log.e(TAG, "error thread");
}
// TODO
}
};
thread.start();
if(d.getLastUpdateTime()!=formatter.format(currentDate.getTime())){
//Put up the Yes/No message box
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle("Must be updated..")
.setMessage("Update?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(d.getLastUpdateTime());
// Toast.makeText(YesNoSampleActivity.this, "Yes button pressed",
// Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", null) //Do nothing on no
.show();
}//if sonu
这是我在carreate的主要课程。启动时,它必须在线程中等待12秒,然后在对话框中询问用户。但是在带有真实设备平板电脑的android studio中,只要应用程序进入屏幕,它就会问。为什么呢?
我做了同步但仍然相同。
修改
根据答案,我改为处理方法。因为我不想使用方法来调用此对话框,所以在oncreate中进行所有声明,因为。
final Handler handler = new Handler(); // this handler will run your code
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (d.getLastUpdateTime() != formatter.format(currentDate.getTime())) {
//Put up the Yes/No message box
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder
.setTitle("db update...")
.setMessage("db?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(d.getLastUpdateTime());
// Toast.makeText(YesNoSampleActivity.this, "Yes button pressed",
// Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", null) //Do nothing on no
.show();
}//if sonu };
}
};
handler.postDelayed(runnable,3000); // here you define a delay
错误:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activi
builder
这一行。
答案 0 :(得分:1)
您的代码无法按预期运行,因为您尝试创建的AlertDialog
中未显示Thread
。发生的事情是:你创建并启动Thread
,它会运行并等待一段时间。同时,在不同的线程中构建并显示对话框。这就是关于线程的事情。
要修复您的代码,我建议您创建一个Handler
实例并使用its postDelayed method,一个Runnable
实例来显示您的对话框,并启动您的Runnable
延迟Handler
:
Handler handler = new Handler(); // this handler will run your code
Runnable runnable = new Runnable() { /* your dialog shows here */ };
handler.postDelayed(runnable, 12000); // here you define a delay
在12秒后,您的代码将被执行。希望这会有所帮助。
修改强>
Here你可以看一下处理一些限制的另一种方法。