简体   繁体   中英

My application stops responding

So whenever I launch my app on my devices it runs fine but when I push a button it does nothing excepted stay highlited and then pops up saying its not responding here is the code. I think its the way I have the code in the OnClickListerner. package com.dicamillo.alarm;

import java.util.Calendar;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.TimePicker;

public class AlarmlockActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    TimePicker tp;
    Button set;
    int hour;
    int minuet;
    DigitalClock dc;
    Calendar calendar = Calendar.getInstance();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tp = (TimePicker) findViewById(R.id.tpAlarmTime);
    set = (Button) findViewById(R.id.bSet);
    dc = (DigitalClock) findViewById(R.id.digitalClock1);
    hour = calendar.get(Calendar.HOUR);
    minuet = calendar.get(Calendar.MINUTE);
    set.setOnClickListener(this);

}

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.bSet:
        while (tp.getCurrentHour().intValue() != hour
                && tp.getCurrentMinute().intValue() != minuet) {
            tp.getCurrentHour().intValue();
            tp.getCurrentMinute().intValue();
            if (tp.getCurrentHour().intValue() == hour
                    && tp.getCurrentMinute().intValue() == minuet) {
                MediaPlayer mp = MediaPlayer.create(AlarmlockActivity.this,
                        R.raw.alarm);
            } 
        }
        break;
    }
}

}

Anything in the onClick method runs on the UI thread. Your while loop is hanging the app and the OS is (rightfully) forcing it to stop.

Look into using an AsyncTask to get your code off the UI thread. You should also pause after each loop iteration to avoid unnecessary CPU usage.

Your while will basically loop forever on the main UI thread until the hour/minute from your TimePicker matches the current time. That's what's causing the ANR message from the OS.

You shouldn't be running long operations on the UI thread. Either use Threads or Handlers or AsyncTasks to achieve the result you want.

你试过检查logcat吗?!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM