Android基础入门,推荐书籍还是郭神的《第一行代码》。有点Java基础,然后照着书看一遍、敲一遍,Android也就算入门了。这里记录下自己看《第一行代码(第2版)》遇到的坎。

先自报下电脑:Thinkpad S5,Windows10 64位


一、创建模拟器报错


报错信息为:


androidstudio dex androidstudio的虚拟机的代码标题_解决方法


Intel HAXM is required to run this AVD.

VT-x is disabled in BIOS.

Enable VT-x in your BIOS security settings (refer to document for your computer).


即:VT-x处于禁用状态,需要打开。与AS开发环境无关,需要在BIOS中打开。

解决方法:重启电脑--开机界面出现Lenovo时,按下Enter键--按下F1键,进入BIOS--选择Security--选择Virtualization--进入后将Intel(R) Virtualization Technology,置为Enabled--按下F10键保存并退出。电脑启动后即可。



二、Android Studio运行报错


安装完AS,第一次创建项目,运行报错。我的AS是3.0.1版本。


报错信息为:

java.util.concurrent.ExecutionException:com.android.tools.aapt2.Aapt2Exception:AAPT2 error:check logs for details Execution failed for task ':app:mergeDebugResources'.

>Error:java.util.concurrent.ExecutionException:com.android.tools.aapt2.Aapt2Exception:AAPT2 error:check logs for details

找到两种解决方法:

方法1:在gradle.properties中加入下面代码:

android.enableAapt2=false

自己没有用这个方法。因为这个方法有个缺陷,每创建一个项目都要加这一行依赖,我比较懒,嫌太麻烦。

方法2:将C盘下的用户名,改为英文。没错,就是中文名文件夹导致的问题。Windows10安装时,当用户使用微软账号登录,则Win10就会以这个中文名建立用户文件夹。少数软件安装或使用过程中,不支持中文路径,从而报错,无法使用。所以,为了一劳永逸,不再出现这种caodan的问题,建议将用户文件夹改为英文。用户文件夹名修改方法可以参考:https://jingyan.baidu.com/article/27fa732689e0eb46f8271f27.html。修改时需要切换到Administrator用户登录,而Win10为了保证系统安全,默认禁用了Administrator账户,启用方法可以参考:https://jingyan.baidu.com/article/36d6ed1f7eee861bcf4883ac.html。


三、响应打开网页Intent的问题

《第一行代码》中有一个示例,让自己的Activity响应http的action,但编译不通过:

Activity supporting ACTION_VIEW is not set as BROWSABLE.
Ensure the URL is supported by your app,to get installs and traffic to your app from Google Search.

没有将activity设置为browsable,因为category可以指定多个,这里添加一个browsable的category就可以:

<activity android:name=".ThirdAcitivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <data android:scheme="http"/>
    </intent-filter>
</activity>


四、打开对话框式的活动

《第一行代码》中的一个示例,通过点击Button打开DialogActivity运行报错:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.activitylifecycletest/com.example.activitylifecycletest.DialogActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

错误提示中指出我们需要用Theme.AppCompat的主题,这是因为我们的DialogActivity继承了AppCompatActivity,需要用与其配合的theme才行。找到两种解决方法:

方法1:使用Theme.AppCompat的主题,修改如下:

<activity android:name=".DialogActivity"
    android:theme="@style/Theme.AppCompat.Dialog">
</activity>

注意,这里是@style,不是@android:style。重新编译,运行正常。


方法2:如果不需要继承AppCompatActivity,可以直接继承Activity,修改如下:

public class DialogActivity extends Activity {