资源描述
Android实验指导
实验一:系统安装与HelloWorld
【目的】
安装智能手机开发相关软件平台。
【要求】
1、 完成智能手机开发平台安装、以与相关配置
2、 并实现Hello World
3、 了解项目的基本文件目录结构
【原理】
Eclipse安装原理,Android编程方法
【过程】
1、 安装JAVA JDK
下载 java.sun./javase/downloads/
2、 安装Eclipse
下载 .eclipse.org/downloads/
3、 安装Android
developer.android.或androidappdocs.appspot./index.html
4、 安装ADT(Android Development Tools)
developer.android.或androidappdocs.appspot./index.html
5、 安装手机USB驱动
developer.android.或androidappdocs.appspot./index.html
如果用模拟器调试,则可暂时不装。
6、 建立新项目,实现Hello World。
Open Eclipse.
Click the menu File -> New -> Project.
Expand the Android folder and select Android Project.
Name the project HelloWorld
得到的文件结构如下:
运行:
选运行的设备,可以是模拟器,也可以是真机(如果已经连接好真实手机的话):
真手机
模拟器
模拟器运行:
真实手机调试:
实验二:界面设计:控件与布局
【目的】
Android编程基础,UI设计。
【要求】
1、 了解Android编程原理
2、 掌握界面控件设计
3、 掌握控件的事件处理编程
【原理】
UI设计原理
【过程】
1、 了解各种控件的基本功能
各种控件:
Menu
TextView、EditText、
Button
Radio button
List
ProgressBar;
2、 了解布局Layout的应用
多种Layout:
AbsoluteLayout
FrameLayout
GridView
LinearLayout
ListLayout
RadioGroup
TableLayout
………
3、 利用布局安排各种控件,设计良好用户界面
<LinearLayoutxmlns:android="schemas.android./apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextViewandroid:id="+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="string/hello"
/>
<EditTextandroid:id="+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageViewandroid:id="+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="drawable/adr"
/>
<LinearLayoutandroid:id="+id/LinearLayout01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Buttonandroid:id="+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="string/btn_name"
/>
<Buttonandroid:id="+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="string/stp_name"
/>
</LinearLayout>
<ProgressBarandroid:id="+id/progressbar01"
android:layout_width="fill_parent"
android:layout_height="20px"
style="?android:attr/progressBarStyleHorizontal"
/>
<SeekBarandroid:id="+id/seekbar01"
android:layout_width="fill_parent"
android:layout_height="20px"
style="?android:attr/progressBarStyleHorizontal"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="schemas.android./apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="android:drawable/editbox_background"
android:layout_below="id/label"/>
<Button
android:id="+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="id/ok"
android:layout_alignTop="id/ok"
android:text="Cancel"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="schemas.android./apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<AnalogClock
android:id="+id/aclock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<DigitalClock
android:id="+id/dclock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="id/aclock"
android:layout_alignLeft="id/aclock"
android:layout_marginLeft="40px"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="当前时间:"
android:layout_toLeftOf="id/dclock"
android:layout_alignTop="id/aclock"/>
</RelativeLayout>
实验三:图形绘制与OpenGL
【目的】
在屏幕绘制各种图形,了解OpenGL
【要求】
1、 了解在屏幕绘图方法
2、 了解OpenGL
【原理】
【过程】
1、 绘制直线、园、曲线等各种图形
2、 显示字符
3、 利用OpenGL编程方法
publicvoid onDrawFrame(GL10 gl) {
//一般的opengl程序,首先要做的就是清屏
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
//紧接着设置模型视图矩阵
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();//清空矩阵
GLU.gluLookAt(gl, 0, 0, 3, 0, 0, 0, 0, 1, 0);//视点变换,将相机位置设置为(0, 0, 3),同时指向(0, 0, 0)点
//设置模型位置旋转与缩放信息
gl.glTranslatef(0.0f, 0.0f, -1.0f);//将模型位置设置为(0, 0, -1)
float angle = 30.0f;
gl.glRotatef(angle, 0, 1, 0);//绕模型自身Y轴旋转30度
gl.glRotatef(angle, 1, 0, 0);//绕模型自身X轴旋转30度
gl.glScalef(1.2f, 1.2f, 1.2f);//设置三方向的缩放系数
//设置颜色
gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
//渲染立方体
mCube.draw(gl, gl.GL_TRIANGLES);
//mCube.draw(gl, gl.GL_LINES);
}
实验四:网络访问与服务
【目的】
掌握Android网络访问方法
【要求】
1、 了解手机WEB访问编程
2、 通过网络进行数据访问
3、 了解数据库使用
【原理】
利用Android网络访问协议
【过程】
1、 访问WEB,通过 Response类,读入网络数据。
Client client = new Default Client();
Get get = new Get(url);
Response response = client.execute(get);
Entity entity = response.getEntity();
//尝试读取entity的长度,返回-1表示长度未知
long length = entity.getContentLength();
InputStream is = entity.getContent();
String s = null;
if (is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = newbyte[512];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
//如果长度已知,可以通过taskProgress()通知监听者任务执行的比例
if (length > 0) {
listener.taskProgress(this, count, length);
}
//为了更好的演示进度,让线程休眠100ms
Thread.sleep(100);
}
Log.e(" Task", "length=" + baos.toByteArray().length);
//返回容
s = new String(baos.toByteArray());
}
return s;
读入.google.数据:
实验五:硬件访问与传感器
【目的】
通过底层API访问手机硬件与手机上的各种传感器
【要求】
1、 获取手机上、短信等各种功能的编程
2、 了解手机上各种传感器的功能与使用方法
【原理】
利用手机本身的功能与相关传感器的使用
【过程】
1、 了解程序使用手机功能的方法
短信收发:
package .android.TinySMS;
import android.app.Activity;
import;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
publicclass TinySMS extends Activity {
publicstaticfinal String SMS_ACTION = ".android.TinySMS.RESULT";
// private TextView message;
private Button snd;
private EditText tel;
private EditText txt;
private SentReceiver receiver = new SentReceiver();
privateclass SentReceiver extends BroadcastReceiver {
Override
publicvoid onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_ACTION)) {
int code = getResultCode();
//短消息发送成功
if(code == Activity.RESULT_OK)
Toast.makeText(TinySMS.this, R.string.msg_sent,
Toast.LENGTH_SHORT).show();
}
}
};
/** Called when the activity is first created. */
Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tel = (EditText) findViewById(R.id.EditText01);
tel.setText("5554"); //模拟器之间互发短信
txt = (EditText) findViewById(R.id.EditText02);
txt.setText("我用自己的程序试试发短信。");
snd = (Button) findViewById(R.id.Button01);
snd.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View arg0) {
String phoneNo = tel.getText().toString();
String message = txt.getText().toString();
if (phoneNo.length()>0 && message.length()>0){
sendSMS(phoneNo, message);
} else {
Toast.makeText(TinySMS.this,
"请重新输入和短信容",
Toast.LENGTH_LONG).show();
}
}
});
}
privatevoid sendSMS(String address, String content)
{
SmsManager manager = SmsManager.getDefault();
Intent i = new Intent(SMS_ACTION);
//生成PendingIntent,当消息发送完成,接收到广播
PendingIntent sentIntent = PendingIntent.getBroadcast(
this,
0,
i,
PendingIntent.FLAG_ONE_SHOT);
manager.sendTextMessage(
address,
null,
content,
sentIntent,
null);
}
}
如果要发短信,还需在AndroidManifest.xml中声明权限:
<uses-permissionandroid:name="android.permission.READ_SMS"></uses-permission>
<uses-permissionandroid:name="android.permission.SEND_SMS"></uses-permission>
2、 手机上有多种传感器,可以对这些传感器进行编程。
相机拍摄:
package .android.cameraAndroid;
import android.app.Activity;
import android.os.Bundle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.media.AudioManager;
import android.media.ToneGenerator;
import .Uri;
import android.os.Environment;
import android.os.StatFs;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraAndroid extends Activity {
private CameraPreview preview;
private Camera camera;
private ToneGenerator tone;
private static final int OPTION_SNAPSHOT = 0;
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preview = new CameraPreview(this);
setContentView(preview);
}
Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch(itemId){
case OPTION_SNAPSHOT:
//拍摄照片
camera.takePicture(shutterCallback, null, jpegCallback);
break;
}
return true;
}
//返回照片的JPEG格式的数据
private PictureCallback jpegCallback = new PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera) {
Parameters ps = camera.getParameters();
if(ps.getPictureFormat() == PixelFormat.JPEG){
//存储拍照获得的图片
String path = save(data);
//将图片交给Image程序处理
Uri uri = Uri.fromFile(new File(path));
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setDataAndType(uri, "image/jpeg");
startActivity(intent);
}
}
};
//快门按下的时候onShutter()被回调
private ShutterCallback shutterCallback = new ShutterCallback(){
public void onShutter() {
if(tone == null)
//发出提示用户的声音
tone = new ToneGenerator(AudioManager.STREAM_MUSIC,
ToneGenerator.MAX_VOLUME);
tone.startTone(ToneGenerator.TONE_PROP_BEEP2);
}
};
private String save(byte[] data){
String path = "/sdcard/"+System.currentTimeMillis()+".jpg";
try {
//判断SD卡上是否有足够的空间
String storage = Environment.getExternalStorageDirectory().toString();
StatFs fs = new StatFs(storage);
long available = fs.getAvailableBlocks()*fs.getBlockSize();
if(available<data.length){
//空间不足直接返回空
return null;
}
File file = new File(path);
if(!file.exists())
//创建文件
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return path;
}
Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, OPTION_SNAPSHOT, 0, R.string.snapshot);
return super.onCreateOptionsMenu(menu);
}
class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
public CameraPreview(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
//Sureface创建的时候,此方法被调用
public void surfaceCreated(SurfaceHolder holder) {
//打开摄像头,获得Camera对象
camera = Camera.open();
try {
//设置显示
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
camera = null;
}
}
//Surface销毁的时候,此方法被调用
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
//释放Camera
camera.release();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
//已经获得Surface的width和height,设置Camera的参数
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
//开始预览
camera.startPreview();
}
}
}
拍摄模拟:
实验六:开发Android APPs的语音功能
【目的】
掌握Android APPs的语音库的调用方法
【要求】
1、 了解TTS(Text-To-Speech)的基本概念
2、TTS Market的安装
3、TTS语音库的调用方法
【原理】
通过调用TTS语音库实现将字符串转为声音读出。
【过程】
1、eclipse中导入TTS库的引用
2、下载并安装TTS Market
3、调用TTS方法实现语音读出
1、配置Esclipse的设定:
Project > Properties > Java Build Path > Libraries and click on"Add External JARs..." 然后增加 TTS_library_stub.jar文件
2、使用eSpeak引擎前需要为Emulator添加虚拟SD Card。
3、下载tts_market.apk 将这个APK安装到Emulator (启动Emulator的前提下,在CLS中输入”adb install ***.APK “)。当程序运行后也可以通过参数控制是否需要弹出安装tts_market.apk的提示对话框:
4、实现调用语音库的方法:
1)创建一个新的Android项目,可以随意命名为你认为有意义的名字,比如“I am Well-E”等等
2)应用上边所提到的方法为当前的项目添加Library。
3)在主程序.java中添加如下代码:
import .google.tts.TTS;
private TTS myTts; //介于onCreate()和类之间声明空的TTS
myTts = new TTS(this, ttsInitListener, true); //在onCreat()后边定义一个新函数
//在onCreat()中创建TTS的实体
private TTS.InitListener ttsInitListener = new TTS.InitListener() {
public void onInit(int version) {
myTts.speak("I am Wall E", 0, null);
}
};
至此可以Run你的程序了,如果顺利的话,第一次启动程序后会首先调用TTS通过Server下载数据,然后手动回到主程序面板重新启动你的程序,听到Emulator发出响亮的声音了吧?
注意:
创建TTS实体时要求有三个参数:
1. Application Context
2. TTS.InitListener - 监听TTS初始化Event
3. Boolean - 当检测到Emulator或其它测试机没有安装TTs_market.apk时,是否弹出下载 提示对话框。
TTS实体调用Speak行为时的参数:
1. String - 语音容
2. Boolean - 是否启用队列模式(0:代表没有列队模式,1:代笔具有先进先出的队列模式)
3. Array - an array of Strings that are parameters for how to speak the text.
23 / 23
展开阅读全文