Запущено второе нежелательное действие - PullRequest
0 голосов
/ 03 апреля 2012

У меня простая игровая активность.Я запускаю его и затем нажимаю кнопку возврата.Когда она нажата, она вызывает finish ().После я снова запускаю игру.Я перехожу через onCreate () и воссоздаю глобальные переменные, которые у меня есть, но затем я получаю широковещательную рассылку от другого класса, и когда я отлаживаю ее, я нахожусь в другой деятельности, называемой деятельностью $ 1, а предыдущей была операция $ 0.Могу ли я заставить убить первого, когда я вызываю finish ()?Или как я могу получить уже работающий экземпляр с установленными переменными из второго?

Мой код приведен ниже с некоторыми комментариями

public class actvty extends Activity {

private LocalBroadcastManager brdcst_manager;
private BroadcastReceiver receiver;
private RelativeLayout lay;
private BallView ball_view;
private RingView ring_view;
private Background bg;
private CounterVIew counter_view;
private long startTime;
private int count_games = 0;
private List<Integer> turns = new ArrayList<Integer>(), times = new ArrayList<Integer>();

public final static String FINISHED = "com.blq.blq.blq.finished", EXIT = "com.blq.blq.blq.exit";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startTime = System.currentTimeMillis();

    //This manager is used to handle broadcasts within the application
    brdcst_manager = LocalBroadcastManager.getInstance(this.getApplicationContext());

    //Set the main layout
    setContentView(R.layout.main);

    //Get the layout from the resources
    lay = (RelativeLayout) findViewById(R.id.Layout);

    //Set the game to full screen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    //Create the background for the game 
    bg = new Background(this.getApplicationContext());

    //Create the counter view
    counter_view = new CounterVIew(this.getApplicationContext());

    //Create the rings and add them to the stage
    ring_view = new RingView(this.getApplicationContext());

    //Create the balls
    ball_view =  new BallView(this.getApplicationContext(), ring_view);

    //Display the first picture
    counter_view.display_next();

    //Add the views to the stage
    lay.addView(bg);
    lay.addView(counter_view);
    lay.addView(ring_view);
    lay.addView(ball_view);

    //Add the events that we are going to listen for to the filter
    IntentFilter filter = new IntentFilter();
    filter.addAction(FINISHED);
    filter.addAction(EXIT);

    //Create the receiver
    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(FINISHED)) {
                //HERE IS THE PROBLEM... WHEN I RESTART THE GAME I GO THROUGH THE onCreate AND I CREATE THE GLOBAL VARIABLES
                //BUT HERE THEY ARE ALL NULL WHEN I DEBUG IT
                Log.v("asdasd", FINISHED);
                reset_game();
            } else if(intent.getAction().equals(EXIT)) {
                finish();
            }
        }
    };

    //Register the listener
    brdcst_manager.registerReceiver(receiver, filter);
}

protected void reset_game() {
//HERE IS THE PROBLEM... WHEN I RESTART THE GAME I GO THROUGH THE onCreate AND I CREATE THE GLOBAL VARIABLES
//BUT HERE THEY ARE ALL NULL
//ALSO WHEN THIS CHRASHES BECAUSE OF THE NULL VARIABLES I GET A MESSAGE IN THE LOG CAT THAT SAYS THAT
//THE INTENT WAS TRIGGERED BY "ACTIVITY$0" AND WAS RECEIVED BY "ACTIVITY$1" WHICH MAKES ME THINK THAT
//I'VE SOMEHOW GOT ANOTHER ONE WHILE THE FIRST ONE IS STILL OPEN
    turns.add(new Integer(ball_view.getCount_turns()));
    times.add(new Integer((int)(System.currentTimeMillis() - startTime)/1000));
    count_games++;
    ball_view.display_newxt();
    counter_view.display_next();
    try {
        lay.invalidate();
        ball_view.invalidate();
        counter_view.invalidate();
        lay.invalidate();
        Thread.sleep(5000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    counter_view.display_next();

    startTime = System.currentTimeMillis();

    //PRINT FOR TESTING
    Log.v("TURNS!!!!!!", turns.toString());
    Log.v("CHRONOMETER!!!", times.toString());
    Log.v("NUMBER OF GAMES!!!!", String.valueOf(count_games));
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        finish();
    }
    return super.onKeyDown(keyCode, event);
  }

@Override
protected void onDestroy() {
//IF I DO NOT NULL THE VARIABLES HERE THAN WHEN I RESTART THE APPLICATION 5 TO 10 TIMES DEPENDING ON THE RESOLUTION
//I GET AN ERROR OOM AND MY BITMAP IS TOO BIG... :(
    super.onDestroy();

    lay.removeAllViews();
    bg.destroy();
    counter_view.destroy();
    ring_view.destroy();
    ball_view.destroy();
    bg = null;
    counter_view = null;
    ring_view = null;
    ball_view = null;
    System.gc();

Спасибо, заранее.

1 Ответ

0 голосов
/ 06 апреля 2012

Я нашел проблему. Даже если старая активность все еще остается в памяти, если я отменим регистрацию получателя в onDestroy, он по крайней мере не получит вызов, и все будет хорошо. :) Я думаю, что если я обнулю переменную, я должен обнулить их всех, а не только тот раз, что мне нужно:)

...