第一篇:关于Android 开发环境的构建方法总结
关于Android开发环境的构建方法总结
作者: 曹亮 发布时间: 2010-03-25 21:31 阅读: 745 次 原文链接 字体: 大 中 小 [收藏]
本方法适用于Android SDK 2.1环境下的程序开发
安装JDK
• 在java.sun.com下载JDK并安装。
• 在“系统属性”的“高级”选项卡中点击“环境变量”,然后添加如下系统环境变量:
1.在PATH环境变量后追加 JDK安装路径中的bin路径,本机为: C:Program FilesJavajdk1.6.0_18bin 2.新建CLASSPATH环境变量或在CLASSPATH环境变量后追加JDK安装路径中的lib路径和demo路径,本机为:
C:Program FilesJavajdk1.6.0_18demo;C:Program FilesJavajdk1.6.0_18lib 安装Eclipse
• 在eclipse.org下载Eclipse IDE for Java Developers的Windows 32bit版本。
• 下载完成后解压即可使用。
安装Android SDK OR 离线安装
• 在Android Developers下载android-sdk_r05-windows.zip,下载完成后解压到任意路径。
• 运行SDK Setup.exe,点击Available Packages,如果没有出现可安装的包请点击Settings,选中Misc中的“Force https://...”这项,再点击Available Packages。
• 选择希望安装的SDK及其文档或者其它包,点击Installation Selected、Accept All、Install Accepted,开始下载安装所选包
• 添加SDK安装目录中的tools文件夹路径至系统PATH环境变量,本机为: C:Androidandroid-sdk-windowstools 关于离线安装
用上面方法更新的时候速度很慢。
更要等很久。所以我们可以直接把那些包下载下来安装。地址就是 https://dl-ssl.google.com/androi...2.0_r01-windows.zip https://dl-ssl.google.com/androi...2.1_r01-windows.zip https://dl-ssl.google.com/androi...-1.1_r1-windows.zip https://dl-ssl.google.com/androi...1.5_r03-windows.zip https://dl-ssl.google.com/androi...1.6_r02-windows.zip https://dl-ssl.google.com/androi...ver_r03-windows.zip https://dl-ssl.google.com/androi...ogle_apis-6_r01.zip https://dl-ssl.google.com/androi...ogle_apis-5_r01.zip https://dl-ssl.google.com/androi...ogle_apis-4_r02.zip https://dl-ssl.google.com/androi...ogle_apis-7_r01.zip 下完之后,名字以android的,解压到platforms里面; 以google_apis开头的,解压到addons里面。usb 驱动的,直接解压到根目录。
安装Eclipse插件 ADT
• Start Eclipse, then select Help > Install New Software.• In the Available Software dialog, click Add...• In the Add Site dialog that appears, enter a name for the remote site(for example, “Android Plugin”)in the “Name” field.In the “Location” field, enter this URL: https://dl-ssl.google.com/android/eclipse/ 如 果无法通过上面的地址获得插件,可将https替换为http。(https is preferred for security reasons)• Back in the Available Software view, you should now see “Developer Tools” added to the list.• Select the checkbox next to Developer Tools, which will automatically select the nested tools Android DDMS and Android Development Tools.Click Next.• In the resulting Install Details dialog, the Android DDMS and Android Development Tools features are listed.• Click Next to read and accept the license agreement and install any dependencies, then click Finish.• Restart Eclipse.配置ADT
在Eclipse中:
• 选择Window > Preferences...• 在左边的面板选择Android,然后在右侧点击Browse...并选中SDK路径,本机为:
C:Androidandroid-sdk-windows • 点击Apply、OK。配置完成。创建AVD
为使Android应用程序可以在模拟器上运行,必须创建AVD。
• 在Eclipse中。选择Windows > Android SDK and AVD Manager • 点击左侧面板的Virtual Devices,在右侧点击New • 填入Name,选择Target的API,SD Card大小任意,Skin随便选,Hardware目前保持默认值
• 点击Create AVD即可完成创建AVD Create a New Android Project
After you've created an AVD, the next step is to start a new Android project in Eclipse.1.From Eclipse, select File > New > Project.If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled “Android” which should contain “Android Project”.(After you create one or more Android projects, an entry for “Android XML File” will also be available.)2.Select “Android Project” and click Next.3.Fill in the project details with the following values: o Project name: HelloAndroid o Application name: Hello, Android o Package name: com.example.helloandroid(or your own private namespace)o Create Activity: HelloAndroid o Min SDK Version: 7 Click Finish.Here is a description of each field:
Project Name
This is the Eclipse Project name — the name of the directory that will contain the project files.Application Name
This is the human-readable title for your application — the name that will appear on the Android device.Package Name
This is the package namespace(following the same rules as for packages in the Java programming language)that you want all your source code to reside under.This also sets the package name under which the stub Activity will be generated.Your package name must be unique across all packages installed on the Android system;for this reason, it's very important to use a standard domain-style package for your applications.The example above uses the “com.example” namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity.Create Activity
This is the name for the class stub that will be generated by the plugin.This will be a subclass of Android's Activity class.An Activity is simply a class that can run and do work.It can create a UI if it chooses, but it doesn't need to.As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application.Min SDK Version(这个是 设置程序希望运行在的系统版本)================================== Tips: 这里的Min SDK Version会根据我们选择的Build Target改变,表示程序将运行在哪个系统版本之上,对应的数值关系如下: Android 1.5:Level API 3 Android 1.6:Level API 4 Android 2.01:Level API 6 Android 2.1:Level API 7 我们这里选择Android 2.1,故Min SDK Version为7
================================== This value specifies the minimum API Level required by your application.If the API Level entered here matches the API Level provided by one of the available targets, then that Build Target will be automatically selected(in this case, entering “2” as the API Level will select the Android 1.1 target).With each new version of the Android system image and Android SDK, there have likely been additions or changes made to the APIs.When this occurs, a new API Level is assigned to the system image to regulate which applications are allowed to be run.If an application requires an API Level that is higher than the level supported by the device, then the application will not be installed.Other fields: The checkbox for “Use default location” allows you to change the location on disk where the project's files will be generated and stored.“Build Target” is the platform target that your application will be compiled against(this should be selected automatically, based on your Min SDK Version).Notice that the “Build Target” you've selected uses the Android 1.1 platform.This means that your application will be compiled against the Android 1.1 platform library.If you recall, the AVD created above runs on the Android 1.5 platform.These don't have to match;Android applications are forward-compatible, so an application built against the 1.1 platform library will run normally on the 1.5 platform.The reverse is not true.Your Android project is now ready.It should be visible in the Package Explorer on the left.Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid).It should look like this: 下面是点完Finish按钮之后自动生成的代码: package com.example.helloandroid;import android.app.Activity;import android.os.Bundle;public class HelloAndroid extends Activity { /** Called when the activity is first created.*/ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);setContentView(R.layout.main);} } Notice that the class is based on the Activity class.An Activity is a single application entity that is used to perform actions.An application may have many separate activities, but the user interacts with them one at a time.The onCreate()method will be called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup.An activity is not required to have a user interface, but usually will.Now let's modify some code!构建 UI
Take a look at the revised code below and then make the same changes to your HelloAndroid class.The bold items are lines that have been added.下面让我们修改一下代码:
package com.android.helloandroid;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class HelloAndroid extends Activity { /** Called when the activity is first created.*/ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);TextView tv = new TextView(this);tv.setText(“Hello, Android”);setContentView(tv);} } 执行代码:Hello,Android
Eclipse的插件使得你的程序很容易运行。选择Run>Open Run Dialog菜单。(Eclipse3.4版本中,菜单为Run->Run Configurations)可以看到这样的对话框。
下一步,选择“Android Application”,点击在左上角(按钮像一张纸上有个“+”号)或者双击“Android Application”。有个新的选项“New_configuration”。
将名字改得更形象一点,如“Hello,Android”,然后按Browse按钮选择你的项目,(如果你Eclipse里有多个Android项 目需要打开,确定要选择正确)插件会会自动扫描你项目里的活动子类,然后在“活动”的下拉菜单里加载。如果你的“Hello,Android”项目只有一 个,它将被设置为默认项目,然后你可以继续。
点击“Apply”按钮,这里有个例子: 这样就可以了,点击“Run”按钮,Android的模拟器启动。一启动你的程序就会出现,当一切OK,你可以看到: 这样就可以了,点击 “Run”按钮,Android的模拟器启动。启动完毕后你的程序就会出现,如果不出现,有时候是因为有键盘锁的原因,用鼠标将 键盘锁解开就一切OK,你可以看到:Hello Android.使用XML构建UI
你刚 刚完成的“Hello, World”的例子使用的是我们称为“可编程”的UI层,意思是你通过编写代码来组建UI层。当你开发了足够多的UI程序,你会发现一些很糟糕的现象: 一些小的变化需要你做大量的代码改动。你常常会忘记将View连接起来,这样会导致一些错误,浪费你很多时间去调试代码。这就是Android为 什么提供一个可变化的UI开发模块:基于XML的文件。最简单解释这个概念就是演示个例子。这里有个XML的文件,它能达到和你刚才完成代码同样的效果:
在这个例子里,有4个XML属 性,下面是属性的大概意思:
xmlns:android 这是一个XML命名空间,告诉Android开发工具你准备使用Android命名空间里的一些通用属性。在所有Android XML设计文件中最外层的标记必须使用这个属性。
android:layout_width 这个属性定义了这个视图需要占用的屏幕宽度。在这个例子中,我们仅有的一个视图可以占用整个屏幕,那就是“fill_parent”的意思。
android:layout_height 这个和“layout_width”差不多,表示占用屏幕的高度。
android:text 这个设置文本显示内容,在这个例子里,我们使用“Hello,Android”。
这就是XML的布局,你需要把这个文件放在什么位 置? 放在你的工程/res/layout下就可以。“res”是“resource”的简称,这个目录包含了所有应用程序需要的非代码部分。比如图片、字符 串、XML文件。
Eclipse插件为你创建了这些XML文件中的一个。在我们上面的范例,我们根本没有使用过它。在包的管理器里,展开 目录/res/layout,编辑main.xml文件,替换上面的文本然后保存修改。
在从代码目录里打开 HelloAndroid/gen/com.example.helloandroid/R.java文件,你可以看到他们像这样: public final class R { public static final class attr { };public static final class drawable { public static final int icon=0x7f020000;};public static final class layout { public static final int main=0x7f030000;};public static final class string { public static final int app_name=0x7f040000;};};R.java是文件中所有资源的索引界定值定义。你在代码中使用这个类,就像在你的项目里使用一个简洁的方法表示你 的资源。在Eclipse这样的IDE工具里,这个方式对于代码自动完成功能还是非常有效的,因为这能让你快速得定位你要寻找的东西。
有个重要点 需要注意的是有个内部类“main”,是“layout”的成员类。Eclipse插件提醒你加了一个新的XML文件,然后生成R.java文件,当你加 入其他资源到你的工程里,你可以看到R.java在同步更改。
第二篇:厦门手机开发培训关于Android开发环境的构建方法总结
厦门手机开发培训关于Android开发环境的构建方法总结
厦门博看文思本方法适用于AndroidSDK2.1环境下的程序开发
安装JDK
•在java.sun.com下载JDK并安装。
•在“系统属性”的“高级”选项卡中点击“环境变量”,然后添加如下系统环境变量:
1.在PATH环境变量后追加JDK安装路径中的bin路径,本机为:
C:ProgramFilesJavajdk1.6.0_18bin
2.新建CLASSPATH环境变量或在CLASSPATH环境变量后追加JDK安装路径中的lib路径和demo路径,本机为:
C:ProgramFilesJavajdk1.6.0_18demo;C:ProgramFilesJavajdk1.6.0_18lib安装Eclipse
•在eclipse.org下载EclipseIDEforJavaDevelopers的Windows32bit版本。•下载完成后解压即可使用。
安装AndroidSDKOR离线安装
•在AndroidDevelopers下载android-sdk_r05-windows.zip,下载完成后解压到任意路径。
•运行SDKSetup.exe,点击AvailablePackages,如果没有出现可安装的包请点击Settings,选中Misc中的“Forcehttps://...”这项,再点击AvailablePackages。
•选择希望安装的SDK及其文档或者其它包,点击InstallationSelected、AcceptAll、InstallAccepted,开始下载安装所选包
•添加SDK安装目录中的tools文件夹路径至系统PATH环境变量,本机为:C:Androidandroid-sdk-windowstools
关于离线安装
用厦门博看文思上面方法更新的时候速度很慢。
更要等很久。所以我们可以直接把那些包下载下来安装。
地址就是
https://dl-ssl.google.com/androi...2.0_r01-windows.zip
https://dl-ssl.google.com/androi...2.1_r01-windows.zip
https://dl-ssl.google.com/androi...-1.1_r1-windows.zip
https://dl-ssl.google.com/androi...1.5_r03-windows.zip
https://dl-ssl.google.com/androi...1.6_r02-windows.zip
https://dl-ssl.google.com/androi...ver_r03-windows.zip
https://dl-ssl.google.com/androi...ogle_apis-6_r01.zip
https://dl-ssl.google.com/androi...ogle_apis-5_r01.zip
https://dl-ssl.google.com/androi...ogle_apis-4_r02.zip
https://dl-ssl.google.com/androi...ogle_apis-7_r01.zip
下完之后,名字以android的,解压到platforms里面;
以google_apis开头的,解压到addons里面。
usb驱动的,直接解压到根目录。
安装Eclipse插件ADT
•StartEclipse,thenselectHelp>InstallNewSoftware.•IntheAvailableSoftwaredialog,clickAdd...•
IntheAddSitedialogthatappears,enteranamefortheremotesite(forexample,“AndroidPlugin”)inthe“Name”field.Inthe“Location”field,enterthisURL:
https://dl-ssl.google.com/android/eclipse/
如果无法通过上面的地址获得插件,可将https替换为http。
(httpsispreferredforsecurityreasons)
BackintheAvailableSoftwareview,youshouldnowsee“DeveloperTools”addedtothelist.•
SelectthecheckboxnexttoDeveloperTools,whichwillautomaticallyselectthenestedtoolsAndroidDDMSandAndroidDevelopmentTools.ClickNext.•
IntheresultingInstallDetailsdialog,theAndroidDDMSandAndroidDevelopmentToolsfeaturesarelisted.•
ClickNexttoreadandacceptthelicenseagreementandinstallanydependencies,thenclickFinish.•RestartEclipse.配置ADT
在Eclipse中:
•选择Window>Preferences...•在左边的面板选择Android,然后在右侧点击Browse...并选中SDK路径,本机为:C:Androidandroid-sdk-windows
•点击Apply、OK。配置完成。
创建AVD
为使Android应用程序可以在模拟器上运行,必须创建AVD。
•在Eclipse中。选择Windows>AndroidSDKandAVDManager
•点击左侧面板的VirtualDevices,在右侧点击New
•填入Name,选择Target的API,SDCard大小任意,Skin随便选,Hardware目前保持默认值
•点击CreateAVD即可完成创建AVD
第三篇:Eclipse android开发环境搭建总结
环境组成:Eclipse4.2+JDK 1.6+Android SDK v21+ ADT
一、安装Eclipse + JDK
Eclipse是一款免费开源的开发工具,它提供的仅仅是一个框架,其特点在于插件开发,即它可以添加插件,根据不同的功能需求只需安装相应的插件即可。
Eclipse是一款轻量级的插件,直接点击exe文件即可运行,不需安装,不需写入注册表等各种操作。据说3.8版本性能要高于4.2.Eclipse本身并不包括JDK,(MyEclipse也是如此)因此还要自己安装JDK。JDK包括一些可执行文件和类库,比如JAVA编译器、JRE(java运行时环境,即java虚拟机,java程序运行比不可少)。据说JDK1.6运行速度要比其他版本要好很多。JDK可直接运行,安装完之后,还要添加环境变量,这里我有点疑惑,书上写的和网上查的不一样,为保险起见我取了并集: 首先添加Path=C:Program FilesJavajdk1.6.0_24bin和C:Program FilesJavajdk1.6.0_24jre bin,然后添加classPath=C:Program FilesJavajdk1.6.0_24lib和C:Program FilesJavajdk1.6.0_24libtools.jar.这样JDK安装完毕。
二、Android SDK安装
首先下载Android SDK,我在网上随便搜的,好像这个SDK要与Eclipse版本匹配才行,因此在搜时要注明Eclipse的版本。然后运行SDK Manager,这才是真正的下载Android SDK,文件很多,速度超级慢,得几个小时。网上有快的方法,但是挺复杂。下载的内容主要是各个SDK版本的platform以及API。然后添加该文件夹下的tools文件夹目录添加到path环境变量中。
三、Eclipse安装ADT
ADT是一个插件,google开发的方便在Eclipse下进行安卓开发的插件,其实用记事本程序同样可以开发安卓程序,只不过这样更方便。
这要利用Eclipse的自动下载功能,方法是在Eclipse菜单中选择安装新软件,然后输入https://dl-sll.google.com/android/eclipse,然后会自动搜索相关软件。我刚开始选择全部安装,但是每次都失败,后来只选择了DDMS和android development tools就成功了。
这样开发环境就搭建好了。
Ps.然后还要创建android开发的模拟器,这个要用到AVDM,网上很多教程,很简单就搜到,我也没搞清楚怎么回事,只是按照步骤创建成功了。
第四篇:Android项目开发总结
项目开发总结报告
1引言
1.1编写目的
总结开发经验与学习中的不足
1.2背景
以方便用户记录日常学习心得,生活体会为目的,进行主题为“随心笔记”的应用开发
2实际开发结果
2.1产品
2.2主要功能和性能
能够查看笔记的目录,记录笔记完成时间。能够改变主题颜色,目录排版方式,拥有简洁的主题。对于涂鸦功能,插入图片,密码锁等功能未能实现。
3开发工作评价
3.1对产品质量的评价
本应用拥有简单实用的功能,能够满足一般用户的需要
3.3对技术方法的评价
开发中使用了软件工程中的增量开发模型,黑盒测试等技术,使开发逐步向前发展
3.4出错原因的分析
对于部分Android版本支持性不好,不能正常使用安装等
4经验与教训
通过这次开发,我们体验了开发不易,需要很多人员的合作。开发过程中,必须明确整体目标,不能东一榔头,西一棒槌。另外由于学习时间短,对很多东西都不太了解,还好通过CSDN等一些网站能够找到有益的帮助,感谢那些博客,论坛。
第五篇:Android开发基本知识总结-Android课件
Android开发基础教程
2015-4-13周一2CJ02 目录
1.什么是Android? 2.Android应用开发环境 3.Gradle 4.模拟器Emulator 5.开发一个安卓应用程序的步骤 6.关于多个模拟器的问题 7.安卓工程文件的结构 8.android界面文件---xml文件 9.android程序文件---java文件 10.界面布局方式 11.几个常用组件 12.Roast组件 13.对话框AlertDialog 14.几条重要的语句 15.监听器Listener 16.识别响应事件的组件 17.界面切换
18.界面之间的数据传递 19.Activity生命周期 20.多媒体播放
21.日志文件在程序调试中的使用 22.使用XML文件保存数据
23.使用TXT文件保存数据 24.使用数据库保存数据 25.时间组件 26.线程Thread 27.视频播放VideoView 28.MediaPlayer,SurfaceView和SurfaceHolder播放视频 29.录制音频MediaRecorder 30.菜单组件
1.什么是Android? 移动设备(常常指手机mobile)的操作系统,由google公司出品,是免费的, 最早是基于Linux平台的;目前已经推出的Android3.0是平板电脑上的操作系统。
其它的手机操作系统有:iPhone系统等。
手机厂商:三星(Samsung,宏达电(HTC),摩托罗拉(Motorola),华硕,索尼,Garmin等都支持iPhone系统。
Android系统功能:自定义用户界面,支持蓝牙,多点触摸,具有导航功能和语音识别功能,结合了google地图。
Android软件开发工具SDK
4.0。
Android系统特点:虚拟键盘,以WebKit为核心的WebView组件,可以使用HTML, javascript等。
2.Android应用开发环境 Eclipse+ADT+Android SDK。ADT---Android开发工具插件(Android Plugs for Eclipse).开发环境安装注意事项:关闭防毒软件,按顺序安装,保持网络畅通,比较耗时。特别说明,安装和运行需要高配置机器和高速网络,比较费时。
(1)安装Java
JDK。甲骨文
网站: http://www.xiexiebang.com ”);Intent in = new Intent(Intent.ACTIN_VIEW, uri);startActivity(in);(2)调用系统拨号界面
Uri uri = Uri.parse(“tel:*** ”);Intent in = new Intent(Intent.ACTIN_DIAL, uri);startActivity(in);(3)调用系统拨号功能
Uri uri = Uri.parse(“tel:*** ”);Intent in = new Intent(Intent.ACTIN_CALL, uri);startActivity(in);注意:需要在AndroidManifest.xml文件中进行设置,才可以自动拨号:
= new Bundle();bndle.pushString(“name”, “David”);bndle.pushInt(“age”, 22);//pushChar, putShort,put Boolean, pushChar等等
Uri uri = Uri.parse(“http://www.xiexiebang.com ”);Intent in = new Intent(Intent.ACTIN_VIEW, uri);in.putExtras(bundle);startActivity(in);在第二个界面中: Intent in = this.get Intent();Bundle bundle
= in.getExtras();String studentName = bundle.getInt();//getDouble, 2.方法2:调用有返回参数 例1,在第一个界面中: private static final int ACTIVITY_EDIT = 1;Bundle bundle = new Bundle();bundle.pushString(“name”, “David”);Intent in = new Intent();
getShort, getIntArray等 in.putExtras(bundle);in.setClass(FullscreenActivity.this, SecondActivity.class);startActivityForResult(in, ACTIVITY_EDIT);注意:startActivityForResult后所有语句无效,不执行;在第一个界面中,第二个界面可以在不同位置被多次调用;在第一个界面中,在其它位置可以调用其它界面。
在第一个界面中,重写onActivityResult,接收所有被调用界面返回的参数(如果有):@Override protected void onActivityResult(int
requestCode,int resultCode,Intent
data){ super.onActivityResult(requestCode, resultCode, data);if(requestCode== ACTIVITY_EDIT)
//此参数可以区分不同的调用
{
Bundle bundle = data.getExtras();if(resultCode == RESULT_OK)
//此参数可以判断有无返回参数
{
Bundle bundle = data.getExtras();……
} if
(resultCode == RESULT_CANCELED)
{ } }
…… } ……
问题
:如何判断被调用界面是否传递返回参数?如何区分返回参数是由不同的被调用界面传递的?android的这种解决方法并不是完美的。例2,在第二个界面中:
读取第一个界面传递的参数,省略;下面是向调用程序传递返回参数: Bundle bundle
= new Bundle();bndle.pushString(“name”, “贺昌峰373780592”);Intent
setResult(RESULT_CANCELED);//传递参数返回
// 或setResult(RESULT_OK, in);//不传递参数返回 finish();注意:这时,第二个界面返回到第一个界面,可以不传递参数直接返回(RESULT_CANCELED),in = new Intent();
in.putExtras(bundle);也可以传递参数返回(RESULT_OK)。19.Activity生命周期
onCreate
---onStart
---onResume
---onPause---onStop
---onDestroy 也就是说,有: protected void oncreate(…){ ….} protected void onStart(…){ ….} protected void onResume(…){ ….} protected void onPause(…){
….} protected void onStop(…){ ….} protected
void onDestroy(…){ ….} 20.多媒体播放MediaPlayer public MediaPlayer player = new MediaPlayer();//生成语句可省略 try{ player.reset();
//重新播放音乐
player.setDataSource(“/sdcard/music/music_file_name.mp3”);
// player = MediaPlayer.create(getApplicationContext(), R.raw.music);
// 打开音乐文件
//music为音乐资源文件
player.prepare();player.start();
// player.isPlaying()
//准备播放 //播放音乐
//判断是否正在播放
//音乐播放完成触发事件
player.setOnCompletionListener(new OnCompletionListener){ public void onCompletion(){ //音乐播放完成后,处理代码 } }
player.pause();player.start();player.stop();
} catch(IllegalStateException e){ ……} catch(IOException e){ ……}
//播放暂停 //继续播放音乐 //停止播放音乐 player.release();
//释放存储空间
//注意:可以播放存储卡上任意一个音乐文件;也可以播放资源列表中的音乐文件 21.日志文件在程序调试中的使用
import android.util.Log;对应的方法有:debug,verbose,info,warn,error。注意,使用简写。问题:如何查看系统日志文件?
Log.d(“这里是分类标签”, “这里是输出信息”);22.使用XML文件保存数据
对XML文件进行操作,形式为(key,value)。SharedPreferences
sp = get SharedPreferences(文件名,权限);
权限:MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE 例:
//1打开XML文件 SharedPreferences
//2更改数据
Editor editor = sp.eidt();
//更改数据
sp = get SharedPreferences(“myconfig”,MODE_PRIVATE);
editor.putString(“name”, “贺昌峰373780592”);editor.putInt(“age”, 48);editor.putFloat(“salary”, 2048.5);//putLong,putBoolean等;
editor.commit();
//保存数据
//3读取数据
String myname = sp.getString(“name”, “”);
//4删除数据
editor.remove(“name”);//删除数据 editor.commit();
editor.clear();//删除全部数据 editor.commit();
//5简写形式如下: Editor editor = sp.eidt()
//更改数据
//读取数据
.putString(“name”,.commit();
“贺昌峰”)23.使用TXT文件保存数据 FileOutPutStream
fout = openFileOutput(文件名, 文件权限);文件权限: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE
1.在文件中写入数据
try { //打开TXT文件 FileOutPutStream
BufferedOutputStream
String
//向文件中写入数据
bufferoutput.write(s.getBytes());s = “大家跟我学习android”;
bufferoutput = new BufferedOutputStream(fout);fout = openFileOutput(“myconfig.txt”, MODE_PRIVATE);
//关闭文件 bufferoutput.close();fout.close();} Catch(Exception e){
2.从文件中读取数据
try { FileInputStream
BufferedInputStream
byte[] bufferbytes = new byte[20];int flag = bufferoutput.read(bufferbytes);if(flag==-1){ //文件读取到文件末尾,否则可以继续读出
}
//仅读取长度为20个字节的数据
bufferoutput = new BufferedInputStream(fout);
fout = openFileInput(“myconfig.txt”);
//打开文件
e.printStackTrace();} bufferoutput.close();fout.close();} Catch(Exception e){
24.使用数据库保存数据 1.数据库相关类
//关闭缓冲区 //关闭文件
e.printStackTrace();} import android.content.ContentValues;import android.content.Context;import android.database.Coursor;import android.database.SQLException;import android.database.sqlite.SQLiteDatabase;
2.SQLiteDataBase类
注意:数据库操作时,要求捕获异常,此处省略。
SQLiteDataBase db = openOrCreateDatabase(“databasename.db”, MODE_PRIVATE);//说明:数据库权限同文件权限
// Context就是this指针 db.execSQL(sql_exp): 执行SQL语句
Cursor cs = db.rawQuery(select_exp, null): 返回数据集。Cursor cs1 = db.query(arg0, ……): 使用较繁琐,可用rawQuery替换。
db.insert(arg0, ……): 使用较繁琐,可用rawQuery替换。db.delete(arg0, ……): 使用较繁琐,可用rawQuery替换。db.update(arg0, ……):
使用较繁琐,可用rawQuery替换
db.close(): 一般写在onDestroy事件中。3.Cursor类 方法有:
move, moveToPosition, moveToFirst, moveToLast,moveToNext, getCount(), getInt(),getString(),isNull(), isFirst()等等。
4.ContentValues类
一般用在SQLiteDataBase.insert中, 此处省略。
ContentValues content
= new ContentValues();
content.put(“name”, “贺昌峰”);
moveToPrevious, content.put(“age”, 48);5.SimpleCursorAdapter类
SimpleCursorAdapter是界面组件如ListView和Cursor的桥梁。例, 在ListView组件listview1中,显示数据集(有绑定功能吗?):
Cursor cs = db.rawQuery(“select SimpleCursorAdapter
adapter
* from table”, null);
= new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2, new String[]{“id”, “name”}, new int[]{ android.R.id.text1, android.R.id.text2});// 注意:第2个参数的作用
listview1.setAdapter(cs);
//在ListView组件显示数据集
25.时间组件
1.常用组件AnalogClock,DigitClock 用法比较简单,无需过多设置,仅仅显示当前时间:机械式,数字式
2.计时组件:Chronometer 常用方法:start开始计时, stop停止计时, setBase设置时间 setFormat(“秒表:%s”):设置组件时间显示格式。
附:与时间格式有关的函数 SimpleDateFormat String
sformat = new SimpleDateFormats(“hh:mm:ss”);
//得得当前时间 s = sformat.format(new Date());
例,Chronometer对象是chroTime: chroTime.setOnChronometerTickListeter(chrolisteten);
private Chronometer.onChronometerTickListeter Chronometer.onChronometerTickListeter(){ @Override public
void OnChronometerTickListeter(Chronometer chronomoter){ //每秒执行一次该方法 } }
3.计时组件Timer和TimerTask
chrolisteten = new 常用函数:schedule(TimerTask对象, Timer对象延迟时间, TimerTask对象间隔时间);
TimerTask对象用法: private TimerTask { public void run(){ //按设定间隔调用执行 handle.sendMessage(msg);//特别注意:此处不能对界面进行更新,因为影响计时精度,所有需要使用Handle配合。见下。} }
4.Handle和Message的配合使用 Handle handle { public void handleMessage(){ super.handleMessage();//进行其它处理 }
= new Handle()
timetask = new TimerTask()} Message
msg.what = “******”;handle.sendMessage(msg);
26.线程Thread
1.Thread的定义
public class ClockThread extends Thread{ @Override public void run(){ //进行其它处理
//注意:不会自动重复执行多次的 } } 2.Thread的启动、延时启动、停止 使用Handle对线程进行控制: msg = new Message();Handle handle = new Handle();
ClockThread clock = new ClockThread();
handle.post(clock);
//启动线程 5000);
//延时5000ms启动线程 //停止线程 handle.postDelayed(clock, handle.removeCallbacks(clock);
问题:使用Handle有什么优点? 27.视频播放VideoView 支持的文件格式:H.264的mp4, wmv, 3gp等。1.视频播放
private VideoView
videoview.setVideoPath(“/sdcard/robot.mp4”);//增加控制面板
videoview.setMediaController(new MediaController(getApplicationContext()));
videoview
= new VideoView();videoview.start();//开始播放
2.视频准备播放事件
videoview.setOnPreparedListener(videoPreparedListener);videoview.setOnCompletionListener(videoCompletionListener);
private MediaPlayer.onPreparedListener videoPreparedListener = new MediaPlayer.onPreparedListener(){ @Override public
void onPrepared(MediaPlayer
mp){ //视频准备播放 } }
3.视频播放完成事件
private MediaPlayer.onCompletionListener videoCompletionListener = MediaPlayer.onCompletionListener(){ @Override public
void onCompletion(MediaPlayer
mp){
new //视频播放完成 } }
28.MediaPlayer,SurfaceView和SurfaceHolder播放视频
MediaPlayer也可以播放视频,需要SurfaceView和SurfaceHolder配合,其中SurfaceView为可视化组件可以播放视频,SurfaceHolder为桥梁。
private SurfaceView surfview = new SurfaceView();//此组件可视化设计,无需这里声明 private MediaPlayer
surfholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);mediaplayer.setDisplay(surfholder);
mediaplayer.setDataSource(“/sdcard/vedio.mp4”);mediaplayer.reset();
//打开视频文件
mediaplayer = new MediaPlayer();
= surfview.getHolder();private SurfaceHolder surfholder
//重新播放视频 mediaplayer.prepare();mediaplayer.start();mediaplayer.stop();mediaplayer.release();
//准备播放视频 //播放视频
29.录制音频MediaRecorder MediaRecorder
mediaRecorder.SetAudioSource(MediaRecorder.AudioSource.MIC);mediaRecorder.SetAudioEncode(MediaRecorder.AudioEncode.DEFAULT);mediaRecorder.SetOutputFormat(MediaRecorder.OutputFormat.DEFAULT);mediaRecorder.SetOutputFile(“/sdcard/recorder.amr”);mediaRecorder.prepare();mediaRecorder.start();
注意:要有写入SD卡的权限,在AndroidManifest.xml文件中:
//准备录音 //开始录音
mediaRecorder = new MediaRecorder(); :
1.附1:ImageView.setAlpha(50)的含义?设置透明色 2.附2:遍历目录下所有文件: private File pathfile;pathfile = Environment.getExternalStorageDirectory();
//疑问:pathfile + ”/myfilename.txt” 这个用法正确吗? for(File file: pathfile.listFiles()){ if {(file.getName().toLowerCase().endsWith(“.amr”))……
// File.getAbsolutePath(), File.getName()的区别 } } 30.菜单组件 //添加系统菜单 protected protected static final int MENU_ABOUT
= Menu.FIRST;static final int MENU_QUIT = Menu.FIRST + 1;
//得到SD卡路经 protected
@Override static final int MENU_EDIT = Menu.FIRST + 2;public boolean onCreateOptionsMenu(Menu menu){ menu.add(0,MENU_ABOUT,0,“关于本软件...”).setShortcut('0','A');
menu.add(0,MENU_QUIT,1,“结束”).setShortcut('1','E');
menu.add(0,MENU_EDIT,2,“编辑”).setShortcut('2','D');
menu.add(0,MENU_FILE,3,“文件”).setShortcut('3','F');
return super.onCreateOptionsMenu(menu);} //添加菜单响应事件 @Override public boolean onOptionsItemSelected(MenuItem switch(item.getItemId()){ case MENU_ABOUT: // 响应处理 break;case MENU_QUIT: // 响应处理 break;}
return super.onOptionsItemSelected(item);}
//添加快捷菜单 protected static final int MENU_BACKCOLOR protected static final int MENU_SMALLSIZE =
item){
= Menu.FIRST;
Menu.FIRST + 1;//定义快捷菜单组件 private LinearLayout private TextView
layout;
txtview1,txtview2;在onCreate中, 增加以下语句: layout =(LinearLayout)findViewById(R.id.layout);txtview1 =(TextView)findViewById(R.id.txtview1);txtview2 =(TextView)findViewById(R.id.txtview2);registerForContextMenu(txtview1);registerForContextMenu(txtview2);
在java文件类中, 增加以下语句: @Override public boolean onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){ //注意:父类函数先调用,或最后调用? super.onCreateOptionsMenu(menu, v, menuInfo);
if(v == txtview1)menu.add(0, MENU_BACKCOLOR,0,“设置背景颜色”); if(v == txtview2)menu.add(0, MENU_SMALLSIZE,1,“较小字体”);
}
//添加菜单响应事件 @Override public boolean onContextItemSelected(MenuItem switch(item.getItemId()){ case MENU_BACKCOLOR: // 响应处理
layout.setBackgroundColor(Color.BLUE);break;case MENU_SMALLSIZE: // 响应处理
txtview2.setTextSize(12);break;}
return super.onContextItemSelected(item);}
item){