setContentView无法在发布apk上使用GoogleApiClient

时间:2016-05-28 09:59:53

标签: java android google-play-games

我最近在我的游戏中实现了Google Play游戏API,但之后出现了一些问题。

问题出于某种原因,当我启动应用程序并调用方法 setContentView() 时,我的游戏没有加载我的自定义视图类,但这只发生在我构建apk的发布版本。

gv = new GameView(this);
setContentView(gv); //not loading on release version or if the debuggable is set to true in build.gradle

我也尝试将此行放在build.gradle

  

debuggable false

结果是发布版本开始工作,但是这行我无法将其上传到playStore,这个线程的原因很明显,因为我需要在playStore上工作。

一些测试说明:

  • Google Play服务很好地连接了发布调试 apks,但在发布时出现了黑屏,而不是我的GameView Class
  • 发布版本上运行apk或在build.gradle中将debuggable设置为true时,setContentView()有效。
  • 调试版本
  • 上运行apk时,setContentView()正常
  • 如果我在任何情况下加载XML文件(但我的游戏不使用任何XML),setContentView()可以正常工作

主要活动类

public class Main extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    GameView gv;

    public static DBHandler db;
    public static String version = "0.0.0";

    public static GoogleApiClient mGoogleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fullScreen(true); //PRE ESTABELECE O TAMANHO DA TELA DEIXANDO NO FULLSCREEN PRIMEIRAMENTE

        (Toast.makeText(this, "inicializando GameView", Toast.LENGTH_SHORT)).show();
        gv = new GameView(this);
        setContentView(gv);

        // Create the Google Api Client with access to the Play Games services
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Games.API).addScope(Games.SCOPE_GAMES)
                // add other APIs and scopes here as needed
                .setViewForPopups(gv)
                .build();
        // ...
        //setContentView(R.layout.loading_screen);

        db = new DBHandler(this);
        Log.w("Main", ""+db.getPointsCount()+" - registros encontrados.");

        //VERSAO ---
        PackageInfo pInfo = null;
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            version = pInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }// ...

    }

    protected void onDestroy(){
        super.onDestroy();
        gv.relase();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        fullScreen(hasFocus);
    }
    void fullScreen(boolean hasFocus){
        if (hasFocus) {
            final View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
    }



    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();

        Log.e("Main","Conectando ao Google Play...");
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();

        Log.e("Main","Desconectado da google API PlayGames!");
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.e("Main","onConnected");
        Games.Achievements.unlock(mGoogleApiClient, "CgkI8au7i4oUEAIQAg");

        (Toast.makeText(this, "Conectado ao Google Play Game", Toast.LENGTH_SHORT)).show();


    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.e("Main","onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.e("Main","onConnectionFailed");
        (Toast.makeText(this, "Não foi posivel conectar ao Google Play Services.", Toast.LENGTH_SHORT)).show();
    }

}

的build.gradle

apply plugin: 'com.android.application'

android {
    signingConfigs {
        DannarkKey {
            keyAlias 'dannark'
            keyPassword '23021994'
            storeFile file('C:/Users/Daniel/AndroidstudioProjects/DannarkKey.jks')
            storePassword '23021994'
        }
    }
    compileSdkVersion 23
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.jumpers.gamelogic"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 24
        versionName "2.7.4"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.google.android.gms:play-services:9.0.0'
}

GameView.class

/**
 * Created by Daniel on 19/03/2016.
 */
public class GameView extends View implements Runnable {
    Context context;
    private static final int INTERVAL = 10;
    private boolean running = true;
    private Paint p;
    public static HUD hud;
    public static PrintText pt;
    public static ArrayList<SpawnMessageWindows> spawnMsgs = new ArrayList<>();
    public static ScoreScreen scoreScreen;
    public static HandleEventsTouchsSpawnedObjects handleEventsTouchs = new HandleEventsTouchsSpawnedObjects();

    public static Load load;
    public static Fase fase;
    public static Player player;
    public static Menu menu;
    public static Camera cam;

    Bitmap layerImg2;
    public static Canvas layer2;
    public static LaterCanvas laterCanvas;

    public static int lar;
    public static int alt;

    public static int touchFocus = 0;

    public static ArrayList<String> variaveisName = new ArrayList<>();
    public static ArrayList<Float> variaveisValue = new ArrayList<>();

    private long preTime = 0;
    public static int timeInGame = 0;

    public static boolean isPlaying = false;

    // blocksIDsUsedForTutorial TEM O OBJETIVO DE MOSTRAR MENSSAGENS DE TUTORIAS PELA PRIMEIRA VES CASO VC NUNCA TENHA USADO
    // UM SCRIPT, SE TIVER DENTRO DESSA LISTA, ENTÃO A MENSAGEM NAO APARECERA.
    public static ArrayList<Integer> blocksIDsUsedForTutorial = new ArrayList<>();

    public GameView(Context context) {
        super(context);
        this.context = context;

        load = new Load(context);

        p = new Paint();
        Thread t = new Thread(this);
        t.setPriority(Thread.MIN_PRIORITY);
        t.start();
        preTime = System.currentTimeMillis()/1000;

        addVariavel("variavel1", 0); //TESTE
        addVariavel("valor3", 0); //TESTE
        addVariavel("valor4", 0); //TESTE
        addVariavel("valor5", 0); //TESTE
        addVariavel("valor6", 0); //TESTE
        addVariavel("valor7", 0); //TESTE
        addVariavel("valor8", 0); //TESTE
    }

    void init(){
        while (getWidth() == 0){ }//aguarndando getWidth
        lar = getWidth();
        alt = getHeight();
        player = new Player();
        fase = new Tutorial_001(context);//new Fase1(context);
        hud = new HUD();
        pt = new PrintText();
        menu = new Menu(context);
        cam = new Camera(getWidth(), getHeight(), player);

        layerImg2 = Bitmap.createBitmap(lar, alt, Bitmap.Config.ARGB_8888);
        layer2 = new Canvas(layerImg2);
        laterCanvas = new LaterCanvas(context);

        setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //int action = event.getActionMasked();

                TextKeyBoard.handleTouch(v, event);
                NumericKeyBoard.handleTouch(v, event);
                hud.handleTouch(v, event);
                menu.handleTouch(v, event);
                cam.handleTouch(v, event);
                handleEventsTouchs.handleTouch(v, event); //SEGURA TODOS OS EVENTOS DE OBJETOS CRIADOS POSTEIORMENTE

                return true;
            }
        });
    }

    @Override
    public void run() {
        init();

        while (running){
            try {
                Thread.sleep(INTERVAL);
            }catch (Exception e){
                Toast t = Toast.makeText(getContext(), "Game Loop:"+e.getMessage(), Toast.LENGTH_LONG);
                t.show();
                Log.e("GameLogic", "GameLoop erro Inesperado: "+e.getMessage());
            }
            update();
        }
    }

    public void update(){
        //dispara o metodo de desenho
        postInvalidate();
        timeInGame = (int)((System.currentTimeMillis()/1000)-preTime); //TEMPO JOGADO EM SEGUNDOS
    }

    public void draw(Canvas c){
        super.draw(c);
        if(c!=null && player != null && hud != null && menu != null && cam!=null) {
            c.drawColor(Color.BLACK);

            if(isPlaying) {
                cam.draw(c, p);

                hud.draw(c, p);
                pt.draw(c, p);

                if(scoreScreen != null) {
                    scoreScreen.draw(c);
                }

                laterCanvas.drawBeforeMsgs(c); //DESENHA TODOS OS DESENHOS SOBREPOSTOS NA MESMA CANVAS.

                if(spawnMsgs.size() > 0){
                    spawnMsgs.get(0).draw(c, p);
                }

                laterCanvas.drawAfterMsgs(c); //DESENHA TODOS OS DESENHOS SOBREPOSTOS NA MESMA CANVAS.
                //c.drawBitmap(layerImg2,0,0,p);

            }else {
                menu.draw(c, p);
            }
        }
    }

    public void relase(){
        running = false;
    }

    public static void addVariavel(String variavelNome, float variavelValor){
        if(variaveisName.contains(variavelNome) == false) {
            variaveisName.add(variavelNome);
            variaveisValue.add(variavelValor);
        }
    }
    public static void removeVariavel(int index){
        variaveisName.remove(index);
        variaveisValue.remove(index);
    }
    public static void setVariavelValor(int valiavelIndex, float variavelValor){
        variaveisValue.set(valiavelIndex, variavelValor);
    }
}

0 个答案:

没有答案