Runnable не работает - PullRequest
       22

Runnable не работает

0 голосов
/ 29 апреля 2020

У меня проблема с Runnable. Это не хочет работать, и я не знаю, в чем проблема, потому что это работает в моем другом приложении ... Может кто-нибудь помочь мне? Просто пример, есть "healt" со значением по умолчанию = 5, для теста я сделал кнопку, когда я нажимаю кнопку, значение healt -1 ... и я хочу запустить Runnable, когда health <5 ... и добавить +1 для здоровья .... для теста я установил Runnable 1 secunds </p>

Вот код:

MainActivity. java

package com.mygame.test;


import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;


import static com.mygame.test.variables.coin;
import static com.mygame.test.variables.health;


public class Main2Activity extends AppCompatActivity {

public static final String PREFS_NAME_MAIN = "mainpref";

TextView coinText, healthText, textView;
Button button3;

private final Context app = this;
private final Handler update = new Handler();
private final Runnable updateHealth = new Runnable()
{
    public void run()
    {
        if (variables.run)
        {
            healthText.setText(""+health);


            update.postDelayed(updateHealth, 500);
        }
        else if (!variables.run) update.removeCallbacksAndMessages(null);
    }
};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main2);

    coinText = findViewById(R.id.coinText);

    healthText = findViewById(R.id.healthText);

    healthText.setText(String.valueOf(health));

    button3 = findViewById(R.id.button3);

    textView = findViewById(R.id.textView);




    Button closeButton = findViewById(R.id.closeButton);
    closeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //finishAffinity();
            startActivity(new Intent(Main2Activity.this, ExitActivity.class));
        }
    });

    Button coinsplusButton = findViewById(R.id.coinsplusButton);
    coinsplusButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //finishAffinity();
            startActivity(new Intent(Main2Activity.this, StoreActivity.class));
        }
    });


    Button level1Button = findViewById(R.id.level1Button);
    level1Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //finishAffinity();
            startActivity(new Intent(Main2Activity.this, Level1Activity.class));
        }
    });


}

public void buttontest(View button3)
{
    if (health > 0) {
        health = health-1;
        healthText.setText(""+health);

    }
    variables.run = true;
    Intent activeClick = new Intent(this, ClickService.class);
    this.startService(activeClick);
    update.post(updateHealth);
    save();


}


@Override
protected void onStart()
{
    super.onStart();
    load();
    textupgrade();
    if (!variables.run)
    {
        variables.run = true;
        Intent activeClick = new Intent(this, ClickService.class);
        this.startService(activeClick);
    }
}

protected void onResume()
{
    super.onResume();
    load();
    textupgrade();
    update.post(updateHealth);

}

private void load()
{
    SharedPreferences varReader = app.getSharedPreferences(PREFS_NAME_MAIN, MODE_PRIVATE);
    variables.run = varReader.getBoolean("run", false);
    coin = varReader.getInt("coin", 0);
    health = varReader.getInt("health", 5);

}

private void save()
{
    SharedPreferences.Editor varReader = app.getSharedPreferences(PREFS_NAME_MAIN, 0).edit();
    varReader.putBoolean("run", variables.run);
    varReader.putInt("coin", coin);
    varReader.putInt("health", health);
    varReader.apply();
}

private void textupgrade(){
    coinText.setText(""+coin);
    healthText.setText(""+health);

}


}

ClickService. java

package com.mygame.test;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;

public class ClickService extends IntentService
{
private final Handler handler = new Handler();
private final Runnable addHealth = new Runnable()
{
    public void run()
    {
        variables.health++;
        if (!variables.run) handler.removeCallbacksAndMessages(null);
        else if (variables.run) handler.postDelayed(addHealth, 1000);
    }
};
public ClickService()
{
    super("ClickService");
}
@Override
protected void onHandleIntent(Intent activeClick)
{
    handler.postDelayed(addHealth, 500);
}
}

переменные. java

package com.mygame.test;

public class variables {
static int coin;
static int health;
static boolean run;


}

1 Ответ

0 голосов
/ 29 апреля 2020

О, я исправил это: D ClickService не был зарегистрирован в AndroidManifest

<service
   android:name=".ClickService"
   android:exported="false" />
...