获取类似-java.lang.RuntimeException的错误:无法在未调用Looper.prepare()的线程内创建处理程序
我正在停止有很多活动的申请。如果用户没有响应特定时间(15分钟),那么在15分钟后我会显示一个对话框询问用户“你还在吗?”如果用户按“否”应用程序应关闭。 我试图在帮助下做到这一点 Application idle time
但我没有创建ControlApplication.java
我直接从我的每个活动中调用了touch()。
并从另一个java文件中调用Waiter类构造函数,这对我的应用程序是全局的。
这是我的代码
Waiter.java
public class Waiter extends Thread
{
private static final String TAG=Waiter.class.getName();
private long lastUsed;
private long period;
private boolean stop;
private Context killContext;
public Waiter( long period, Context context )
{
this.period=period;
stop=false;
killContext = context;
}
public void run()
{
long idle=0;
this.touch();
do
{
idle=System.currentTimeMillis()-lastUsed;
Log.d(TAG, "Application is idle for -------------------------------------->"+idle +" ms");
Log.d(TAG, "lastUsed is -------------------------------------->"+lastUsed +" ms");
Log.d(TAG, "currentTimeMillis is -------------------------------------->"+System.currentTimeMillis() +" ms");
try
{
Thread.sleep(5000); //check every 50 seconds
}
catch (InterruptedException e)
{
Log.d(TAG, "----------------Waiter interrupted!-----------------------------------");
}
if(idle > period)
{
idle=0;
Log.d(TAG, "----------------inside if-----------------------------------");
AlertDialog.Builder killBuilder = new AlertDialog.Builder( killContext );
killBuilder.setMessage("Are you still there ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
android.os.Process.killProcess(
android.os.Process.myPid() );
}
});
Log.d(TAG, "----------------inside if killBuilder.create();;-----------------------------------");
AlertDialog alert = killBuilder.create();
Log.d(TAG, "----------------inside if alert.show();-----------------------------------");
alert.show();
}
}
while(!stop);
Log.d(TAG, "--------------------------------Finishing Waiter thread-----------------------------");
}
public synchronized void touch()
{
lastUsed=System.currentTimeMillis();
}
public synchronized void forceInterrupt()
{
this.interrupt();
}
public synchronized void setPeriod(long period)
{
this.period=period;
}
}
但在alert.show();我超过了错误。请帮忙。
答案 0 :(得分:1)
问题是您正在尝试从非UI线程更新UI,您应该从UI线程更新UI,否则您必须使用Handler
或runOnUiThread()
。
试试这个,
killContext.runOnUiThread(new Runnable() {
@Override
public void run() {
alert.show();
}
});
答案 1 :(得分:1)
AlertDialog
无法在任何上下文中显示。所以你必须确保killContext
扩展Activity
类,现在它就在屏幕上写了。
答案 2 :(得分:0)
最好的方法是AsyncTask
。
简短的方法是调用R unOnUiThread( new runnable)
并在runnable中写入警告对话框相关内容。
替代方式Handler
类实现
答案 3 :(得分:0)
您应该在killContext
字段中存储活动而不是上下文,然后您可以致电runOnUiThread
:
killActivity.runOnUiThread(new Runnable(){public void run(){alert.show();}})
答案 4 :(得分:0)
我还观察到,如果一个进程被放在非ui线程上并且它在没有runOnUiThread的情况下引发警报,它会导致某种类型的挂起并且android ui线程进入ANR ...任何人都有同样的观察结果吗?