当前位置: 动力学知识库 > 问答 > 编程问答 >

android layout - dialog.show() crashes my application, why?

问题描述:

I'm new in adroid.

I like to do things when the color reach a value. I like (for example) show the alert if r is bigger than 30, but the application go in crash. Thank for very simple answares.

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);

}

Inside this loop while running is true. is impossible to show dialogs ??

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();

}

}

网友答案:

you cann't show dialog in thread.you should use handler for this.create a handler in main thread and send it to your thread and instead of dialog.show() in your thread you should send message to handler and in handleMessage method of handler write dialog.show(). example:

Handler handler = new Handler(){ 
@Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case 1:
              dialog.show();
break;
}}};

and send message in thread:

handler.sendEmptyMessage(1);
分享给朋友:
您可能感兴趣的文章:
随机阅读: