Mostrando postagens com marcador android. Mostrar todas as postagens
Mostrando postagens com marcador android. Mostrar todas as postagens

segunda-feira, 6 de março de 2017

Ionic Android - AAPT: No resource found that matches the given name (at 'icon' with value '@drawable/icon')

E aí meu brother que está lendo esse artigo, tudo bom? :)

Rodei o comando "ionic build android" e tive o seguinte erro:

cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-ldpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-mdpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-hdpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-xhdpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-xxhdpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\icon\drawable-xxxhdpi-icon.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-ldpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-mdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-hdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-xhdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-xxhdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-land-xxxhdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-ldpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-mdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-hdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-xhdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-xxhdpi-screen.png
cp: no such file or directory: C:\work\Dropbox\workspaces\ws-ionic\my-app\resources\android\splash\drawable-port-xxxhdpi-screen.png

[...]
:CordovaLib:compileDebugJavaWithJavacNote: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

[...]
:CordovaLib:compileReleaseJavaWithJavacNote: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

:CordovaLib:processReleaseJavaRes UP-TO-DATE
:CordovaLib:transformResourcesWithMergeJavaResForRelease
:CordovaLib:transformClassesAndResourcesWithSyncLibJarsForRelease
:CordovaLib:mergeReleaseJniLibFolders
:CordovaLib:transformNative_libsWithMergeJniLibsForRelease
:CordovaLib:transformNative_libsWithSyncJniLibsForRelease
:CordovaLib:bundleRelease
:prepareComAndroidSupportSupportV42411Library
:prepareDebugDependencies
:compileDebugAidl
:compileDebugRenderscript
:generateDebugBuildConfig
:generateDebugAssets UP-TO-DATE
:mergeDebugAssets
:generateDebugResValues
:generateDebugResources
:mergeDebugResources
:processDebugManifest
:processDebugResourcesC:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\build\intermediates\manifests\full\debug\AndroidManifest.xml:25:23-37 : AAPT: No resource found that matches the given name (at 'icon' with value '@drawable/icon').
 FAILED


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\work\Dropbox\android\sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace
 option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED

Total time: 40.179 secs
ERROR building one of the platforms: Error code 1 for command: cmd with args: /s,/c,"C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\gradlew cdvBuildDebug -b C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true"
You may not have the required environment or OS to build this project
Error: Error code 1 for command: cmd with args: /s,/c,"C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\gradlew cdvBuildDebug -b C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true"

Para resolver fiz o seguinte:
- Fui na pasta /platforms/android/res
- Criei uma pasta chamada "drawable"
- Coloquei um arquivo png qualquer chamado icon.png

Pronto, resolveu :)

Não sei se é a melhor solução, provavelmente não hahah Talvez seja algum conflito de versão ou versão desatualizada de algo (do sdk talvez)...
Como não sou eu que vou gerar o aplicativo para a play store, estou só resolvendo uns bugs aqui, então pra mim, essa solução foi suficiente... Talvez pra vc não tenha sido, mas acredito que posso ter te ajudado a pelo menos entender melhor o problema.

Fonte: http://stackoverflow.com/questions/4736523/no-resource-found-that-matches-the-given-name

Abraço!
Adriano Schmidt

Ionic Android - "Could not resolve all dependencies for configuration" e "Could not find any version that matches com.android.support:support"

Olá :)

Rodei o comando "ionic build android" e tive o seguinte erro:

Running command: C:\work\Dropbox\othertools\node\node.exe C:\work\Dropbox\workspaces\ws-ionic\my-app\hooks\after_prepare\010_add_platform_class.js C:\work\Dropbox\workspaces\ws-ionic\my-app
add to body class: platform-android
Running command: C:\work\Dropbox\othertools\node\node.exe C:\work\Dropbox\workspaces\ws-ionic\my-app\hooks\after_prepare\020_remove_sass_from_platforms.js C:\work\Dropbox\workspaces\ws-ionic\my-app
ANDROID_HOME=C:\work\Dropbox\android\sdk
JAVA_HOME=C:\work\Dropbox\java\windows\jdk1.8.0_60

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.android.support:support-v4:24.1.1+.
     Searched in the following locations:
         https://repo1.maven.org/maven2/com/android/support/support-v4/maven-metadata.xml
         https://repo1.maven.org/maven2/com/android/support/support-v4/
         file:/C:/work/Dropbox/android/sdk/extras/android/m2repository/com/android/support/support-v4/maven-metadata.xml
         file:/C:/work/Dropbox/android/sdk/extras/google/m2repository/com/android/support/support-v4/maven-metadata.xml
         file:/C:/work/Dropbox/android/sdk/extras/google/m2repository/com/android/support/support-v4/
     Required by:
         :android:unspecified

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 23.703 secs
ERROR building one of the platforms: Error code 1 for command: cmd with args: /s,/c,"C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\gradlew cdvBuildDebug -b C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true"
You may not have the required environment or OS to build this project
Error: Error code 1 for command: cmd with args: /s,/c,"C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\gradlew cdvBuildDebug -b C:\work\Dropbox\workspaces\ws-ionic\my-app\platforms\android\build.gradle -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true"

Pra resolver:
- Abra o Android Studio
- Acesse: Tools > Android > SDK Manager
- Clique na aba SDK Tools
- Selecione "Android Support Repository"
- Dê um "Apply"
- Vá seguindo a instalação

Fonte: https://github.com/driftyco/ionic-cloud-issues/issues/107

É isso aí, abraço!
Adriano Schmidt

domingo, 5 de junho de 2016

Failure [INSTALL_FAILED_NO_MATCHING_ABIS]

Hi :)

I tried to install an .apk into a cell phone and I got the error Failure [INSTALL_FAILED_NO_MATCHING_ABIS]

C:\ws-ionic\localhost8080app>adb.exe install -r platforms/android/build/outputs/apk/android-x86-debug.apk
2442 KB/s (33320124 bytes in 13.320s)
        pkg: /data/local/tmp/android-x86-debug.apk
Failure [INSTALL_FAILED_NO_MATCHING_ABIS]

That happened because I should have used the armmv7 version and not the x86 for this cell phone... the cpu architecture of the cell phone was the other one...

With the bellow command, the app was successfully installed

adb.exe install -r platforms/android/build/outputs/apk/android-armv7-debug.apk

Best regards,
Adriano Schmidt

segunda-feira, 2 de maio de 2016

Ionic - It is forbidden to downgrade devices which previously used M permissions

Hi :)

I have a project developed with Ionic, and when the mobile app was being published on play store, one error occurred:

This configuration cannot be published for the following reason(s):
It is forbidden to downgrade devices which previously used M permissions (target SDK 23 and above) to APKs which use old style permissions (target SDK 22 and below). This occurs in the change from version 100062 (target SDK 23) to version 100072 (target SDK 22).
Version 100062 is not served to any device configuration: all devices that might receive version 100062 would receive version 100072.

I don't know if it happened because the last version was generated in another machine or because we've put the crosswalk plugin in our project.

Well, in order to solve this problem, just put this line in your config.xml

<preference name="android-targetSdkVersion" value="23"/>

Maybe you will need to change the "23" for the version you want to use.

After that, you will generate again with "ionic build android --release" and that's all :D

Best regards,
Adriano Schmidt

sexta-feira, 1 de abril de 2016

ionic build android does not update apk files

Hi there,

I ran the command "ionic build android" but the apk files at 'platforms/android/build/outputs/apk' folder were not updated

It started to happen after the crosswalk plugin installation

So, I ran the command "ionic state restore" to delete and fetch the plugins of my package.json and to add the platforms (android and/or ios) again.

After that, when I ran "ionic build android" the apk files were updated, but I realized that I should not use the "android-debug.apk" file like I was used to. Now I must use "android-armv7-debug.apk" or "android-x86-debug.apk" regarding the cell phone processor (ARM or x86).

If you don't know your cell phone processor, try one of the files and if it is the wrong file then a message will be showed to you, and you will close the app, uninstall it, and install it again but with the other file.

These are the commands I am using now:
ionic build android
adb.exe install -r platforms/android/build/outputs/apk/android-armv7-debug.apk

Best regards,
Adriano Schmidt

quarta-feira, 21 de outubro de 2015

Como pegar a localização atual no Android?

Hoje precisei fazer uma app que usava a localização atual, é muito simples!

O projeto inteiro está aqui: https://github.com/adrianoschmidt/android-location-sample

Mas o segredo está nesta classe: MainActivity.java

Basicamente você tem q seguir esses 6 passos:

1) Sua Activity deve implementar as classes GoogleApiClient.ConnectionCallbacks e GoogleApiClient.OnConnectionFailedListener

    public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

2) Criar um atributo do tipo GoogleApiClient

    private GoogleApiClient googleApiClient;

3) No onCreate ou na chamada de um botão você deve verificar se está tudo certo com a API que pega a localização e se estiver construir a API e se conectar nela.

        if (this.checkIfGooglePlayServicesAreAvailable()) {
            this.buildGoogleApiClient();
            this.mGoogleApiClient.connect();
        }

Verificando:

    private boolean checkIfGooglePlayServicesAreAvailable() {
        int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (errorCode != ConnectionResult.SUCCESS) {
            System.out.println("GooglePlayServices errorCode: " + errorCode);
            GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show();
            return false;
        }
        return true;
    }


4) Implementar o método onConnected e pegar a localicação (aqui no exemplo seto em dois TextViews que tenho na minha tela)

    @Override
    public void onConnected(Bundle bundle) {
        TextView textViewLatitude = (TextView) findViewById(R.id.textViewLatitude);
        TextView textViewLongitude = (TextView) findViewById(R.id.textViewLongitude);

        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (mLastLocation != null) {
            textViewLatitude.setText("Lat: " + String.valueOf(mLastLocation.getLatitude()));
            textViewLongitude.setText("Lng: " + String.valueOf(mLastLocation.getLongitude()));
        }
    }

5) Implementar os métodos de suspensão e de falha:

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

6) Solicitar a permissão no manifest

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Basicamente é isso, qualquer coisa baixe o projeto no github ou comenta aqui no post.

Abraço!
Adriano Schmidt

quinta-feira, 15 de outubro de 2015

Atalhos IntelliJ

Opa :)

Eu uso o Eclipse desde sempre... então quando fui usar o IntelliJ IDEA para desenvolver para Android (Android Studio) eu me perdia nos atalhos... então fiz essa tabelinha com os principais atalhos para não me perder :D

O quê 
Eclipse 
IntelliJ 
Deleta a linha 
Ctrl+D 
Ctrl+Y 
Procura por arquivo 
Ctrl+shift+R 
Ctrl+shift+N 
Troca linha de lugar 
Shift+Up/Down 
Alt+shift+Up/Down 
Duplica a linha 
Ctrl+shift+Down 
Ctrl+D 
Navegar entre abas 
Ctrl+PgUp/PgDn 
Alt+Left/Right 
Organizeimports 
Ctrl+Shift+O 
Ctrl+alt+O 
Format 
Ctrl+sfhit+F 
Ctrl+alt+L 

Tem algum atalho que você acha que devia estar nessa lista? Comenta aí :)

Abraço!!
Adriano Schmidt

segunda-feira, 12 de outubro de 2015

Executar comandos linux no Android

Fala galera, precisei executar comandos linux pela minha app Android, para isso usei o código abaixo.

Troque o "date" que é o comando para pegar a data da máquina pelo comando que você quer executar.

No final deste exemplo, peguei o valor retornado e o mostrei em um TextView.

        try {
            String commandLine = "date";
            Process process = Runtime.getRuntime().exec(commandLine);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String value = bufferedReader.readLine();

            TextView dateTextView = (TextView) findViewById(R.id.text_info_line_6);
            dateTextView.setText(value);
        } catch (IOException e) {
            e.printStackTrace();
        }

No GitHub: https://gist.github.com/adrianoschmidt/8c83f972c20358a098a4

Caso você não queira fazer isso programaticamente pode usar o ADB Shell https://developer.android.com/tools/help/shell.html
É bem simples, basta acessar o terminal e ir até a pasta plataform-tools dentro da pasta do SDK do Android "cd <sdk_folder>\platform-tools"
Digite "adb devices" e tendo um dispositivo na lista basta digitar "adb shell" e você já pode digitar os comandos linux.

Vaaleu!
Adriano Schmidt

domingo, 11 de outubro de 2015

Android NDK - Hello World

O NDK é o Native Devolpment Kit e permite você escrever para android usando código nativo através de C ou C++

Geralmente se faz isso para obter mais performance (como é necessário no desenvolvimento de jogos por exemplo)

Mais detalhes em: https://developer.android.com/ndk/index.html

Eu estou usando para ver se consigo acessar recursos de telefonia para fazer uma conference... Mas enfim, segue um Hello World:

Faça o download do NDK: https://developer.android.com/ndk/downloads/index.html

Crie um novo projeto normalmente (File > New > New Project > dê um nome/domínio > Next > Next > Blank/Empty Activity > Finish)

No arquivo local.properties adicione uma linha com o caminho do seu NDK:

        ndk.dir=C\:\\android\\ndk\\android-ndk-r10e

No arquivo gradle.properties adicione isso:
android.useDeprecatedNdk=true

No arquivo build.gradle (da app) adicione em defaultConfig isso:

        ndk {
            moduleName "MyLib"
        }

Verifique se a MainActivity está estendendo diretamente a classe Activity, se não estiver, ajuste.

Na sua activity crie um método assim:
public native String getStringFromNative();

Vá em Build > Make

Depois vá no Terminal do Android Visual Studio e rode esse comando:

cd app\src\main

Depois rode esse comando (Não esquece de trocar as partes em negrito):

javah -d jni -classpath C:\android\sdk\platforms\android-23\android.jar;..\..\build\intermediates\classes\
debug br.com.localhost8080.ndksample.MainActivity

Isso vai criar uma pasta chamada jni com um arquivo .h nela

Crie nessa pasta jni um arquivo chamado main.c com o conteúdo abaixo (não esqueça de trocar os br_com_localhost8080_ndksample_MainActivity)

#include "br_com_localhost8080_ndksample_MainActivity.h"

JNIEXPORT jstring JNICALL Java_br_com_localhost8080_ndksample_MainActivity_getStringFromNative
        (JNIEnv * env, jobject obj)
  {
    return (*env)->NewStringUTF(env, "Hello from JNI!");
  }

Cria na mesma pasta um arquivo vazio chamado util.c (isso é necessário pois sem ele dá bug no gradle)

Depois dê um Build > Make

No activity_main.xml adicione um id no TextView:

android:id="@+id/my_textview"

Coloque na sua Activity

    static {
        System.loadLibrary("MyLib");
    }

No final do onCreate coloque:

        TextView tv = (TextView) findViewById(R.id.my_textview);
        tv.setText(getStringFromNative());

Dê um play e veja seu lindo HelloWorld escrito em C



Fontes no meu github: https://github.com/adrianoschmidt/ndk-sample

Para fazer esse hello world eu segui esse vídeo-tutorial (eh um pouco antigo, então peguei uns bugs que não apareceram no vídeo, e está em inglês): https://software.intel.com/en-us/videos/using-the-ndk-with-android-studio

Abraço!
Adriano Schmidt

Permissions no Android

Pessoal, hoje, na minha app Android, eu estava tentando fazer uma ligação. Dessa forma:

    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:456"));
        startActivity(intent);
    }


Mas deu o erro:

Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{3e464e1 3861:br.com.localhost8080.myapp/u0a62} (pid=3861, uid=10062) requires android.permission.CALL_PHONE

Então fui no AndroidManifest.xml e coloquei a permission:

        <uses-permission android:name="android.permission.CALL_PHONE"/>


Mas aí aconteceu o erro:

Caused by: java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{ea870e6 4476:br.com.localhost8080.myapp/u0a62} (pid=4476, uid=10062) with revoked permission android.permission.CALL_PHONE

Para resolver usei o código abaixo pois a permission CALL_PHONE é level dangerous e você precisa solicitar permissao para o usuário:

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;

    public void onClick(View view) {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            callPhone();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    callPhone();
                }
            }
        }
    }

    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:456"));
        startActivity(intent);
    }

Mais detalhes sobre permissões no android: https://developer.android.com/training/permissions/index.html

Mais detalhes sobre esse processo de ter que solicitar permissões: https://developer.android.com/training/permissions/requesting.html