我是adroid的新手。 当颜色达到一定值时,我喜欢做事。我喜欢(例如)如果r大于30则显示警报,但应用程序崩溃。感谢非常简单的answare。
public class MainActivity extends Activity {
private AlertDialog dialog;
private AlertDialog.Builder builder;
private BackgroundColors view;
public class BackgroundColors extends SurfaceView implements Runnable {
public int grand=0;
public int step=0;
private boolean flip=true;
private Thread thread;
private boolean running;
private SurfaceHolder holder;
public BackgroundColors(Context context) {
super(context);
}
运行时在此循环内是真的。是不可能显示对话框的?
public void run() {
int r = 0;
while (running){
if (holder.getSurface().isValid()){
Canvas canvas = holder.lockCanvas();
if (r > 250)
r = 0;
r += 10;
if (r>30 && flip){
flip=false;
// *********************************
dialog.show();
// *********************************
// CRASH !!
}
try {
Thread.sleep(300);
}
catch(InterruptedException e) {
e.printStackTrace();
}
canvas.drawARGB(255, r, 255, 255);
holder.unlockCanvasAndPost(canvas);
}
}
}
public void start() {
running = true;
thread = new Thread(this);
holder = this.getHolder();
thread.start();
}
public void stop() {
running = false;
boolean retry = true;
while (retry){
try {
thread.join();
retry = false;
}
catch(InterruptedException e) {
retry = true;
}
}
}
public boolean onTouchEvent(MotionEvent e){
dialog.show();
return false;
}
protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld){
super.onSizeChanged(xNew, yNew, xOld, yOld);
grand = xNew;
step =grand/15;
}
}
public void onCreate(Bundle b) {
super.onCreate(b);
view = new BackgroundColors(this);
this.setContentView(view);
builder = new AlertDialog.Builder(this);
builder.setMessage("ciao");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Log.d("Basic", "It worked");
}
});
dialog = builder.create();
}
public void onPause(){
super.onPause();
view.stop();
}
public void onResume(){
super.onResume();
view.start();
}
}
答案 0 :(得分:0)
你不能在thread中显示对话框。你应该使用处理程序。在主线程中创建一个处理程序并将其发送到你的线程而不是你的线程中的dialog.show()你应该发送消息给处理程序和in handleMessage方法的处理程序写入dialog.show()。 例如:
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case 1:
dialog.show();
break;
}}};
并在线程中发送消息:
handler.sendEmptyMessage(1);