Libgdx — Как реализовать экран загрузки в лаунчере Android с помощью рекламы

#java #android #libgdx #google-play-services #screen

#java #Android #libgdx #google-play-сервисы #экран

Вопрос:

Итак, я создал игру, используя Libgdx, и времени загрузки практически не было, недавно я добавил таблицу лидеров Facebook, используя расширение GDXFacebook, что добавило небольшие накладные расходы при загрузке приложения, поскольку оно автоматически входит в систему при загрузке, но ничего, что действительно повлияло на время загрузки. Теперь, используя и внедряя Libgdx, я добавил рекламу через сервисы Google Play на главную страницу игры, но это сделало так, что начальное время загрузки теперь составляет добрых 5 секунд.

Мой вопрос в том, можно ли добавить загрузочное изображение в класс Android Launcher во время его загрузки на главный экран?

Заранее спасибо!

Вот мой класс запуска Android и основной класс игры.

Android Launcher:

 public class AndroidLauncher extends AndroidApplication implements        IActivityRequestHandler {

private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/6300978111";
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;


private AdView adView;

protected Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_ADS: {
                adView.setVisibility(View.VISIBLE);
                break;
            }
            case HIDE_ADS: {
                adView.setVisibility(View.GONE);
                break;
            }
        }
    }
};
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    config.useCompass = false;
    config.useAccelerometer = false;

    RelativeLayout layout = new RelativeLayout(this);

    // Do the stuff that initialize() would do for you
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);


    load(config, layout);

    // Hook it all up
    setContentView(layout);

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();


}


private void load(AndroidApplicationConfiguration config, RelativeLayout layout){
    // Create the libgdx View
    View gameView = initializeForView(new Game(this), config);

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    // Create and setup the AdMob view
    adView = new AdView(this); // Put in your secret key here
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId(AD_UNIT_ID);

/** if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }**/

    //AdRequest adRequest = new AdRequest.Builder().setLocation(locationManager.getLastKnownLocation(locationProvider)).build();
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

    // Add the libgdx view
    layout.addView(gameView);

    // Add the AdMob view
    RelativeLayout.LayoutParams adParams =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
    adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    adView.setY(RelativeLayout.ALIGN_PARENT_BOTTOM - 80);

    showAds(false);
    layout.addView(adView, adParams);

}



@Override
public void onResume() {
    super.onResume();
    if (adView != null) adView.resume();
}

@Override
public void onPause() {
    if (adView != null) adView.pause();
    super.onPause();
}


@Override
public void onDestroy() {
    if (adView != null) adView.destroy();
    super.onDestroy();
}

@Override
public void showAds(boolean show) {
    handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}

/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
public Action getIndexApiAction() {
    Thing object = new Thing.Builder()
            .setName("AndroidLauncher Page") // TODO: Define a title for the content shown.
            // TODO: Make sure this auto-generated URL is correct.
            .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
            .build();
    return new Action.Builder(Action.TYPE_VIEW)
            .setObject(object)
            .setActionStatus(Action.STATUS_TYPE_COMPLETED)
            .build();
}

@Override
public void onStart() {
    super.onStart();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client.connect();
    AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
    super.onStop();

    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    AppIndex.AppIndexApi.end(client, getIndexApiAction());
    client.disconnect();
}
 

Класс игры:

 public class Game implements ApplicationListener{

private int m_ScreenWidth;
private int m_ScreenHeight;

private IActivityRequestHandler requestHandler;


private GameScreen m_GameScreen;
private MenuScreen m_Menu;
private HighScoreScreen m_HighScores;
private RankingsScreen m_RankingScreen;
private Input m_Input;
private Assets m_Assets;

private ShapeRenderer m_ShapeRenderer;
private SpriteBatch m_BatchRenderer;
private OrthographicCamera m_Camera;
private boolean m_Loaded;

public enum State {
    READY, MENU, RUNNING, PAUSED, HIGHSCORE, RANKINGS
}

private State m_State;

public Game(IActivityRequestHandler handler){
    requestHandler = handler;
}

@Override
public void create() {

    m_ScreenWidth = 360;
    m_ScreenHeight = 640;


    m_Camera = new OrthographicCamera();
    m_Camera.setToOrtho(false, 360, 640);
    m_Camera.position.set(m_ScreenWidth / 2, m_ScreenHeight / 2, 0);
    m_Camera.update();

    m_ShapeRenderer = new ShapeRenderer();
    m_BatchRenderer = new SpriteBatch();
    m_BatchRenderer.setProjectionMatrix(m_Camera.combined);
    m_ShapeRenderer.setProjectionMatrix(m_Camera.combined);

    m_Loaded = false;

    m_Assets = new Assets();
    m_Assets.loadAssets();

    while (!m_Loaded) {
        if (m_Assets.getAssetManager().update()) {
            m_Loaded = true;
        }
    }


    m_GameScreen = new GameScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
    m_Menu = new MenuScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
    m_HighScores = new HighScoreScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
    m_RankingScreen = new RankingsScreen(m_ScreenWidth, m_ScreenHeight, m_BatchRenderer, m_ShapeRenderer, m_Camera, this, m_Assets);
    m_Input = new Input(this, m_GameScreen, m_HighScores, m_Menu, m_RankingScreen);


    Gdx.input.setInputProcessor(m_Input);

    m_RankingScreen.autologin();

    setState(State.MENU);
}

@Override
public void render() {

    switch (m_State) {
        case PAUSED:
            m_GameScreen.renderBackground();
            m_GameScreen.renderPaused();
            break;
        case HIGHSCORE:
            m_GameScreen.renderBackground();
            m_HighScores.render(Gdx.graphics.getDeltaTime());
            break;
        case MENU:
            m_Menu.render(Gdx.graphics.getDeltaTime());
            break;
        case READY:
            m_GameScreen.renderReady(Gdx.graphics.getDeltaTime());
            break;
        case RUNNING:
            m_GameScreen.render(Gdx.graphics.getDeltaTime());
            break;
        case RANKINGS:
            m_RankingScreen.render();
            break;
    }
}


@Override
public void dispose() {
    m_RankingScreen.logout();
    m_ShapeRenderer.dispose();
    m_BatchRenderer.dispose();
    m_Assets.dispose();
}

@Override
public void resize(int width, int height) {

}

public State getState() {
    return m_State;
}

public void setState(State state) {
    if(state == State.MENU) {
        m_Menu.resetEnemies();
        requestHandler.showAds(true);
    }
    else if(state == State.RANKINGS) {

        m_RankingScreen.refresh();
        requestHandler.showAds(false);
    } else{
        requestHandler.showAds(false);
    }
    m_State = state;
}

public void resetGame() {
    m_GameScreen.reset();
    m_State = State.READY;
}

public void closeGame() {
    Gdx.app.exit();
}

@Override
public void pause() {
    if (m_State == State.RUNNING)
        setState(State.PAUSED);

}

@Override
public void resume() {
    if (!m_Loaded) {
        while (!m_Loaded) {
            if (m_Assets.getAssetManager().update()) {
                m_Loaded = true;
            }
        }
    }
}