37 “机器人”的第六感——传感器
下面给出一个Demo结合理解一下传感器的简单应用。
public class MainActivity extends Activity implements SensorEventListener{
final String TAG = "Sensor";
SensorManager smanager = null;
Sensor sensor = null;
TextView TextInfo = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获得传感器的服务
smanager = (SensorManager) getSystemService(Context.SENSOR_
SERVICE);
//定义一个TextView,显示数据的变化
TextInfo = (TextView)findViewById(R.id.info);
}
@Override
protected void onResume() {
super.onResume();
//注册关于传感器的Listener,关于方位与加速度的传感器
smanager.registerListener( this, smanager.getDefaultSensor
(SensorManager.SENSOR_ACCELEROMETER | SensorManager.SENSOR_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;
synchronized (this){
StringBuffer sb = new StringBuffer();
sb.append("坐标 X:").append(values[0]).append("\n");
sb.append("坐标 Y:").append(values[1]).append("\n");
sb.append("坐标 Z:").append(values[2]).append("\n");
TextInfo.setText(sb.toString());
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG,"传感器: Sensor" + sensor.getName() );
}
@Override
protected void onStop() {
super.onStop();
smanager.unregisterListener(this);
}
}
38 “机器人”通信的核心——SIM卡
(2)编写代码。
编写MainActivity.java:
public class MainActivity extends Activity {
private TelephonyManager phoneManager;
private TextView simView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获得电话相关信息的系统级的服务
phoneManager = (TelephonyManager) getSystemService
(TELEPHONY_SERVICE);
//获得sim卡相关信息
String info = getInfo(phoneManager);
simView = (TextView)findViewById(R.id.siminfo);
simView.setText(info);
}
}
由于获得TelephonyManager信息代码过于拖沓,在这里推荐使用MVC模式,将相关方法放入业务层,或者单独作为一个方法使用。
public static String getInfo(TelephonyManager tM){
StringBuffer sb = new StringBuffer();
//获得SIM卡当前状态
sb.append("SIM当前状态:");
if(tM.getSimState()==TelephonyManager.SIM_STATE_READY)
{
sb.append("正常").append("\n\n");
}
else if(tM.getSimState()==TelephonyManager.SIM_STATE_ABSENT)
{
sb.append("N/A:无SIM卡").append("\n\n");
}
else
{
sb.append("N/A:SIM状态异常").append("\n\n");
}
//获得SIM卡编号
sb.append("SIM编号:");
if(tM.getSimSerialNumber()!=null)
{
sb.append(tM.getSimSerialNumber()).append("\n\n");
}
else
{
sb.append("N/A:获取失败").append("\n\n");
}
//取得SIM卡运营商代码
sb.append("SIM运营商代码:");
if(tM.getSimOperator().equals(""))
{
sb.append("N/A:获取失败").append("\n\n");
}
else
{
sb.append(tM.getSimOperator()).append("\n\n");
}
//获得SIM卡运营商名称
sb.append("SIM运营商名称:");
if(tM.getSimOperatorName().equals(""))
{
sb.append("N/A:获取失败").append("\n\n");
}
else
{
sb.append(tM.getSimOperatorName()).append("\n\n");
}
//获得SIM卡所属国家
sb.append("SIM所属国家:");
if(tM.getSimCountryIso().equals(""))
{
sb.append("N/A:获取失败").append("\n\n");
}
else
{
sb.append(tM.getSimCountryIso()).append("\n\n");
}
//获得手机号码
sb.append("手机号码:");
if(tM.getLine1Number()!=null)
{
sb.append(tM.getLine1Number()).append("\n\n");
}
else
{
sb.append("N/A:获取失败").append("\n\n");
}
return sb.toString();
}
(3)因为要获得相关电话的信息,所以需要在AndroidManifest.xml中添加相关权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
39 让数据在空中传递——蓝牙
MainActivity.java代码如下:
public class MainActivity extends Activity {
//取得默认的蓝牙适配器
private BluetoothAdapter blueAdapter = BluetoothAdapter.
getDefaultAdapter();
//存储搜索到的可连接设备
private List<BluetoothDevice> devicesList = new ArrayList
<BluetoothDevice>();
private int REQUEST_ENABLE_BT = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//检测蓝牙适配器工作是否正常,异常则提示用户
//检测蓝牙适配器是否开启,没有则进行开启
if (blueAdapter == null) {
showToast("请检查你的设备是否具有蓝牙模块或是否正常");
finish();
}
else if (!blueAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.
ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
//开始搜索
private void doDiscovery() {
blueAdapter.startDiscovery();
}
@Override
protected void onStart() {
super.onStart();
//注册接收器
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//开启搜索看见模式,最大时间为300秒
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DUR
ATION, 300);
startActivity(discoverableIntent);
IntentFilter discoveryFilter = new IntentFilter(BluetoothAdapter.
ACTION_DISCOVERY_FINISHED);
registerReceiver(discovery_R, discoveryFilter);
IntentFilter foundFilter = new IntentFilter(BluetoothDevice.
ACTION_FOUND);
registerReceiver(found_R, foundFilter);
doDiscovery();
}
public void showToast(String string){
Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).
show();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (blueAdapter != null) {
blueAdapter.cancelDiscovery();
blueAdapter.disable();
}
}
//向列表中添加已配对的设备
private void addpaired(){
Set<BluetoothDevice> pairedDevices = blueAdapter.
getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
devicesList.add(device);
}
}
}
//广播接收者:当搜索到设备时调用
BroadcastReceiver found_R = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
/* 从intent中取得搜索结果数据 */
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/* 将结果添加到列表中 */
devicesList.add(device);
}
};
//广播接收者:当搜索结束时调用
BroadcastReceiver discovery_R = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
//在停止搜索后,追加已配对的设备
addpaired();
/* 卸载注册的接收器 */
unregisterReceiver(found_R);
unregisterReceiver(this);
}
};
}
40 安装外部程序
编写strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ApkInstallerActivity!</string>
<string name="app_name">APK安装器</string>
<string name="path">你要安装的APK文件名:</string>
<string name="start">开始安装</string>
</resources>
编写main.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/path"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="MyMusicPlayer.apk"
android:id="@+id/filename"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start"
android:id="@+id/button"
/>
</LinearLayout>
编写InstallActivity.java类:
package com.sharpandroid.apkinstaller;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ApkInstallerActivity extends Activity {
private EditText filenameText ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.button);
filenameText = (EditText) this.findViewById(R.id.filename);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filename = filenameText.getText().toString();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(Environment.
getExternalStorageDirectory(), filename)
), "application/vnd.android.package-archive");
startActivity(intent);
}
});
}
}
添加权限,功能清单文件如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sharpandroid.apkinstaller"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label=
"@string/app_name">
<activity android:name=".ApkInstallerActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 在SD Card中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_
UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_
EXTERNAL_STORAGE"/>
<!-- 安装程序权限 -->
<uses-permission android:name="android.permission.INSTALL_
PACKAGES"/>
<uses-sdk android:minSdkVersion="7" />
</manifest>