初次提交

This commit is contained in:
2022-09-19 18:05:01 +08:00
commit 57051fc44b
5401 changed files with 325410 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
Android一词的本义指“机器人”同时也是Google于2007年11月5日宣布的基于Linux平台的开源手机操作系统的名称。该平台由操作系统、中间件、用户界面和应用软件组成号称是首个为移动终端打造的真正开放和完整的移动软件。
平台的开放性,应用程序间的平等性,无界限、快速方便的应用程序开发,不管是给用户还是给应用程序开发人员,都带来了全新的体验。
Android是一个真正意义上的开放性移动开发平台其不仅仅包含上层的用户界面和应用程序还包括底层的操作系统。所有的Android应用程序都运行在虚拟机上程序之间是完全平等的用户可以随意将第三方软件置换掉系统自带的系统软件。
一个应用程序不但可以通过API访问系统提供的功能还可以声明自身的功能供其他应用程序调用。同时Android为开发人员提供了大量的适用库和工具使得开发人员可以快速创建自己的应用程序。
2010年5月27日手机广告公司AdMob发表报告称中国市场上Android手机销量超过苹果iPhone。而在仅仅的2个月后《福布斯》杂志网络版周二刊文指出Android手机销量将达到iPhone销量的3倍。
另一方面Android更加贴近中国公民的购买力Android为不同层次的消费群体量身定做了属于他们的产品。而软件方面Android的软件从无到有在到现在几乎所有的手机软件都能找到Android版本。Android在中国市场的脚步越走越快。
中国拥有全世界最多的人口中国的经济发展速度如日中天得中国市场就得到了天下五分之一的市场Android在中国正在阔步前进未来一片光明。

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample2_1</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Fri Jul 01 07:58:27 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.bn.pp1">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Sample2_1_Activity"
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>
</manifest>

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-7

View File

@@ -0,0 +1,30 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.pp1;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int Button01=0x7f060000;
public static final int Button02=0x7f060001;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class raw {
public static final int musictest=0x7f040000;
}
public static final class string {
public static final int app_name=0x7f050001;
public static final int hello=0x7f050000;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,28 @@
<?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:textSize="18dip"
android:gravity="center"
android:text="即时音效"
/>
<Button
android:text="播放音效"
android:id="@+id/Button01"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="停止播放"
android:id="@+id/Button02"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Sample3_6_Activity!</string>
<string name="app_name">Sample2_1</string>
</resources>

View File

@@ -0,0 +1,71 @@
package com.bn.pp1;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Sample2_1_Activity extends Activity {
SoundPool sp; // 声明SoundPool的引用
HashMap<Integer, Integer> hm; // 声明一个HashMap来存放声音文件
int currStreamId;// 当前正播放的streamId
@Override
// 重写onCreate方法
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // 设置layout
initSoundPool(); // 初始化声音池的方法
Button b1 = (Button) this.findViewById(R.id.Button01); // 获取播放按钮
b1.setOnClickListener // 为播放按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
playSound(1, 0); // 播放1号声音资源且播放一次
// 提示播放即时音效
Toast.makeText(getBaseContext(), "播放即时音效", Toast.LENGTH_SHORT)
.show();
}
});
Button b2 = (Button) this.findViewById(R.id.Button02); // 获取停止按钮
b2.setOnClickListener // 为停止按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
sp.stop(currStreamId); // 停止正在播放的某个声音
// 提示停止播放
Toast.makeText(getBaseContext(), "停止播放即时音效", Toast.LENGTH_SHORT)
.show();
}
});
}
// 初始化声音池的方法
public void initSoundPool() {
sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); // 创建SoundPool对象
hm = new HashMap<Integer, Integer>(); // 创建HashMap对象
hm.put(1, sp.load(this, R.raw.musictest, 1)); // 加载声音文件musictest并且设置为1号声音放入hm中
}
// 播放声音的方法
public void playSound(int sound, int loop) { // 获取AudioManager引用
AudioManager am = (AudioManager) this
.getSystemService(Context.AUDIO_SERVICE);
// 获取当前音量
float streamVolumeCurrent = am
.getStreamVolume(AudioManager.STREAM_MUSIC);
// 获取系统最大音量
float streamVolumeMax = am
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
// 计算得到播放音量
float volume = streamVolumeCurrent / streamVolumeMax;
// 调用SoundPool的play方法来播放声音文件
currStreamId = sp.play(hm.get(sound), volume, volume, 1, loop, 1.0f);
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample2_10</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.bn.pp10">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Sample2_10_Activity"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyDeviceListActivity"
android:label="@string/select_device"
android:theme="@android:style/Theme.Dialog"
android:configChanges="orientation|keyboardHidden" />
</application>
</manifest>

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8

View File

@@ -0,0 +1,51 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.pp10;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int button_scan=0x7f050004;
public static final int button_send=0x7f050006;
public static final int edit_text_out=0x7f050005;
public static final int new_devices=0x7f050003;
public static final int paired_devices=0x7f050001;
public static final int title_new_devices=0x7f050002;
public static final int title_paired_devices=0x7f050000;
}
public static final class layout {
public static final int device_list=0x7f030000;
public static final int device_name=0x7f030001;
public static final int main=0x7f030002;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int bt_not_enabled_leaving=0x7f040003;
public static final int button_scan=0x7f04000d;
public static final int hint=0x7f04000e;
public static final int none_found=0x7f04000a;
public static final int none_paired=0x7f040009;
public static final int not_connected=0x7f040002;
/** DeviceListActivity
*/
public static final int scanning=0x7f040007;
public static final int select_device=0x7f040008;
/** BluetoothChat
*/
public static final int send=0x7f040001;
public static final int title_connected_to=0x7f040005;
public static final int title_connecting=0x7f040004;
public static final int title_not_connected=0x7f040006;
public static final int title_other_devices=0x7f04000c;
public static final int title_paired_devices=0x7f04000b;
}
}

View File

@@ -0,0 +1,40 @@
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView android:id="@+id/title_paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_paired_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="1"
/>
<TextView android:id="@+id/title_new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/title_other_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="2"
/>
<Button android:id="@+id/button_scan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_scan"
/>
</LinearLayout>

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:gravity="center"
>
<EditText android:id="@+id/edit_text_out"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="bottom"
android:hint="@string/hint"
/>
<Button android:id="@+id/button_send"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:text="@string/send"
/>
</LinearLayout>
</LinearLayout>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Sample2_10</string>
<!-- BluetoothChat -->
<string name="send">发送</string>
<string name="not_connected">没有连接到设备</string>
<string name="bt_not_enabled_leaving">蓝牙不可使用,退出程序</string>
<string name="title_connecting">正在连接……</string>
<string name="title_connected_to">已连接: </string>
<string name="title_not_connected">未连接</string>
<!-- DeviceListActivity -->
<string name="scanning">正在扫描设备……</string>
<string name="select_device">选择要连接的设备</string>
<string name="none_paired">没有可配对的设备</string>
<string name="none_found">未找到设备</string>
<string name="title_paired_devices">已配对的设备</string>
<string name="title_other_devices">其它可用设备</string>
<string name="button_scan">扫描设备</string>
<string name="hint">在此输入要发送的信息</string>
</resources>

View File

@@ -0,0 +1,10 @@
package com.bn.pp10;
//用于管理公共常量的常量类
public class Constant {
// 由Service中的Handler发送的消息类型
public static final int MSG_READ = 2;
public static final int MSG_DEVICE_NAME = 4;
// 从Service中的Handler发来的主键名
public static final String DEVICE_NAME = "device_name";
}

View File

@@ -0,0 +1,147 @@
package com.bn.pp10;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
* 设备列表的Activity
*/
public class MyDeviceListActivity extends Activity {
// extra信息名称
public static String EXTRA_DEVICE_ADDR = "device_address";
// 成员变量
private BluetoothAdapter myBtAdapter;
private ArrayAdapter<String> myAdapterPaired;
private ArrayAdapter<String> myAdapterNew;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置窗口
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// 设置为当结果是Activity.RESULT_CANCELED时返回到该Activity的调用者
setResult(Activity.RESULT_CANCELED);
// 初始化搜索按钮
Button scanBtn = (Button) findViewById(R.id.button_scan);
scanBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);// 使按钮不可见
}
});
// 初始化适配器
myAdapterPaired = new ArrayAdapter<String>(this,
R.layout.device_name);// 已配对的
myAdapterNew = new ArrayAdapter<String>(this,
R.layout.device_name);// 新发现的
// 将已配对的设备放入列表中
ListView lvPaired = (ListView) findViewById(R.id.paired_devices);
lvPaired.setAdapter(myAdapterPaired);
lvPaired.setOnItemClickListener(mDeviceClickListener);
// 将新发现的设备放入列表中
ListView lvNewDevices = (ListView) findViewById(R.id.new_devices);
lvNewDevices.setAdapter(myAdapterNew);
lvNewDevices.setOnItemClickListener(mDeviceClickListener);
// 注册发现设备时的广播
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// 注册搜索完成时的广播
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// 获取本地蓝牙适配器
myBtAdapter = BluetoothAdapter.getDefaultAdapter();
// 获取已配对的设备
Set<BluetoothDevice> pairedDevices = myBtAdapter.getBondedDevices();
// 将所有已配对设备信息放入列表中
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
myAdapterPaired.add(device.getName() + "\n"
+ device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired)
.toString();
myAdapterPaired.add(noDevices);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (myBtAdapter != null) {// 确保不再搜索设备
myBtAdapter.cancelDiscovery();
}
// 取消广播监听器
this.unregisterReceiver(mReceiver);
}
// 使用蓝牙适配器搜索设备的方法
private void doDiscovery() {
// 在标题上显示正在搜索的标志
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// 显示搜索到的新设备的副标题
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (myBtAdapter.isDiscovering()) {// 如果正在搜索,取消本次搜索
myBtAdapter.cancelDiscovery();
}
myBtAdapter.startDiscovery();// 开始搜索
}
// 列表中设备按下时的监听器
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
myBtAdapter.cancelDiscovery();// 取消搜索
// 获取设备的MAC地址
String msg = ((TextView) v).getText().toString();
String address = msg.substring(msg.length() - 17);
// 创建带有MAC地址的Intent
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDR, address);
// 设备结果并退出Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// 监听搜索到的设备的BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// 如果找到设备
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 从Intent中获取BluetoothDevice对象
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 如果没有配对,将设备加入新设备列表
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
myAdapterNew.add(device.getName() + "\n"
+ device.getAddress());
}
// 当搜索完成后改变Activity的标题
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (myAdapterNew.getCount() == 0) {
String noDevices = getResources().getText(
R.string.none_found).toString();
myAdapterNew.add(noDevices);
}
}
}
};
}

View File

@@ -0,0 +1,243 @@
package com.bn.pp10;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//用于管理连接的Service
public class MyService {
// 本应用的唯一 UUID
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
// 成员变量
private final BluetoothAdapter btAdapter;
private final Handler myHandler;
private AcceptThread myAcceptThread;
private ConnectThread myConnectThread;
private ConnectedThread myConnectedThread;
private int myState;
// 表示当前连接状态的常量
public static final int STATE_NONE = 0; // 什么也没做
public static final int STATE_LISTEN = 1; // 正在监听连接
public static final int STATE_CONNECTING = 2; // 正在连接
public static final int STATE_CONNECTED = 3; // 已连接到设备
// 构造器
public MyService(Context context, Handler handler) {
btAdapter = BluetoothAdapter.getDefaultAdapter();
myState = STATE_NONE;
myHandler = handler;
}
//设置当前连接状态的方法
private synchronized void setState(int state) {
myState = state;
}
//获取当前连接状态的方法
public synchronized int getState() {
return myState;
}
//开启service的方法
public synchronized void start() {
// 关闭不必要的线程
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
if (myAcceptThread == null) {// 开启线程监听连接
myAcceptThread = new AcceptThread();
myAcceptThread.start();
}
setState(STATE_LISTEN);
}
//连接设备的方法
public synchronized void connect(BluetoothDevice device) {
// 关闭不必要的线程
if (myState == STATE_CONNECTING) {
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
}
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
// 开启线程连接设备
myConnectThread = new ConnectThread(device);
myConnectThread.start();
setState(STATE_CONNECTING);
}
//开启管理和已连接的设备间通话的线程的方法
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// 关闭不必要的线程
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
if (myAcceptThread != null) {myAcceptThread.cancel(); myAcceptThread = null;}
// 创建并启动ConnectedThread
myConnectedThread = new ConnectedThread(socket);
myConnectedThread.start();
// 发送已连接的设备名称到主界面Activity
Message msg = myHandler.obtainMessage(Constant.MSG_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constant.DEVICE_NAME, device.getName());
msg.setData(bundle);
myHandler.sendMessage(msg);
setState(STATE_CONNECTED);
}
public synchronized void stop() {//停止所有线程的方法
if (myConnectThread != null) {myConnectThread.cancel(); myConnectThread = null;}
if (myConnectedThread != null) {myConnectedThread.cancel(); myConnectedThread = null;}
if (myAcceptThread != null) {myAcceptThread.cancel(); myAcceptThread = null;}
setState(STATE_NONE);
}
public void write(byte[] out) {//向ConnectedThread写入数据的方法
ConnectedThread tmpCt;// 创建临时对象引用
synchronized (this) {// 锁定ConnectedThread
if (myState != STATE_CONNECTED) return;
tmpCt = myConnectedThread;
}
tmpCt.write(out);// 写入数据
}
private class AcceptThread extends Thread {//用于监听连接的线程
// 本地服务器端ServerSocket
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmpSS = null;
try {// 创建用于监听的服务器端ServerSocket
tmpSS = btAdapter.listenUsingRfcommWithServiceRecord("BluetoothChat", MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmServerSocket = tmpSS;
}
public void run() {
setName("AcceptThread");
BluetoothSocket socket = null;
while (myState != STATE_CONNECTED) {//如果没有连接到设备
try {
socket = mmServerSocket.accept();//获取连接的Sock
} catch (IOException e) {
e.printStackTrace();
break;
}
if (socket != null) {// 如果连接成功
synchronized (MyService.this) {
switch (myState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// 开启管理连接后数据交流的线程
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
try {// 关闭新Socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//用于尝试连接其他设备的线程
private class ConnectThread extends Thread {
private final BluetoothSocket myBtSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// 通过正在连接的设备获取BluetoothSocket
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
myBtSocket = tmp;
}
public void run() {
setName("ConnectThread");
btAdapter.cancelDiscovery();// 取消搜索设备
try {// 连接到BluetoothSocket
myBtSocket.connect();//尝试连接
} catch (IOException e) {
setState(STATE_LISTEN);//连接断开后设置状态为正在监听
try {// 关闭socket
myBtSocket.close();
} catch (IOException e2) {
e.printStackTrace();
}
MyService.this.start();//如果连接不成功重新开启service
return;
}
synchronized (MyService.this) {// 将ConnectThread线程置空
myConnectThread = null;
}
connected(myBtSocket, mmDevice);// 开启管理连接后数据交流的线程
}
public void cancel() {
try {
myBtSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//用于管理连接后数据交流的线程
private class ConnectedThread extends Thread {
private final BluetoothSocket myBtSocket;
private final InputStream mmInStream;
private final OutputStream myOs;
public ConnectedThread(BluetoothSocket socket) {
myBtSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// 获取BluetoothSocket的输入输出流
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
myOs = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {// 一直监听输入流
try {
bytes = mmInStream.read(buffer);// 从输入流中读入数据
//将读入的数据发送到主Activity
myHandler.obtainMessage(Constant.MSG_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
e.printStackTrace();
setState(STATE_LISTEN);//连接断开后设置状态为正在监听
break;
}
}
}
//向输出流中写入数据的方法
public void write(byte[] buffer) {
try {
myOs.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
myBtSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,141 @@
package com.bn.pp10;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* 用于显示对话的主Activity
*/
public class Sample2_10_Activity extends Activity {
private EditText outEt;// 布局中的控件引用
private Button sendBtn;
private String connectedNameStr = null;// 已连接的设备名称
private StringBuffer outSb;// 发送的字符信息
private BluetoothAdapter btAdapter = null;// 本地蓝牙适配器
private MyService myService = null;// Service引用
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取本地蓝牙适配器
btAdapter = BluetoothAdapter.getDefaultAdapter();
}
@Override
public void onStart() {
super.onStart();
// 如果蓝牙没有开启提示开启蓝牙并退出Activity
if (!btAdapter.isEnabled()) {
Toast.makeText(this, "请先开启蓝牙!", Toast.LENGTH_LONG).show();
finish();
} else {// 否则初始化聊天的控件
if (myService == null)
initChat();
}
}
@Override
public synchronized void onResume() {
super.onResume();
if (myService != null) {// 创建并开启Service
// 如果Service为空状态
if (myService.getState() == MyService.STATE_NONE) {
myService.start();// 开启Service
}
}
}
private void initChat() {
outEt = (EditText) findViewById(R.id.edit_text_out);// 获取编辑文本框的引用
// 获取发送按钮引用,并为其添加监听
sendBtn = (Button) findViewById(R.id.button_send);
sendBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 获取编辑文本框中的文本内容,并发送消息
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
myService = new MyService(this, mHandler);// 创建Service对象
// 初始化存储发送消息的StringBuffer
outSb = new StringBuffer("");
}
@Override
public void onDestroy() {
super.onDestroy();
if (myService != null) {// 停止Service
myService.stop();
}
}
// 发送消息的方法
private void sendMessage(String message) {
// 先检查是否已经连接到设备
if (myService.getState() != MyService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
.show();
return;
}
if (message.length() > 0) {// 如果消息不为空再发送消息
byte[] send = message.getBytes();// 获取发送消息的字节数组,并发送
myService.write(send);
// 消除StringBuffer和编辑文本框的内容
outSb.setLength(0);
outEt.setText(outSb);
}
}
// 处理从Service发来的消息的Handler
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constant.MSG_READ:
byte[] readBuf = (byte[]) msg.obj;
// 创建要发送的信息的字符串
String readMessage = new String(readBuf, 0, msg.arg1);
Toast.makeText(Sample2_10_Activity.this,
connectedNameStr + ": " + readMessage,
Toast.LENGTH_LONG).show();
break;
case Constant.MSG_DEVICE_NAME:
// 获取已连接的设备名称,并弹出提示信息
connectedNameStr = msg.getData().getString(
Constant.DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"已连接到 " + connectedNameStr, Toast.LENGTH_SHORT)
.show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
// 如果设备列表Activity返回一个连接的设备
if (resultCode == Activity.RESULT_OK) {
// 获取设备的MAC地址
String address = data.getExtras().getString(
MyDeviceListActivity.EXTRA_DEVICE_ADDR);
// 获取BLuetoothDevice对象
BluetoothDevice device = btAdapter
.getRemoteDevice(address);
myService.connect(device);// 连接该设备
}
break;
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// 启动设备列表Activity搜索设备
Intent serverIntent = new Intent(this, MyDeviceListActivity.class);
startActivityForResult(serverIntent, 1);
return true;
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample2_2</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Fri Jul 01 07:55:04 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.bn.pp2">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Sample2_2_Activity"
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>
</manifest>

View File

@@ -0,0 +1,11 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-7

View File

@@ -0,0 +1,30 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.bn.pp2;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int Button01=0x7f050000;
public static final int Button02=0x7f050001;
public static final int Button03=0x7f050002;
public static final int Button04=0x7f050003;
public static final int Button05=0x7f050004;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -0,0 +1,43 @@
<?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:gravity="center"
android:text="简单音乐播放器"
/>
<Button
android:text="播放音乐"
android:id="@+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="暂停播放"
android:id="@+id/Button02"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="停止播放"
android:id="@+id/Button03"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="增大音量"
android:id="@+id/Button04"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button
android:text="减小音量"
android:id="@+id/Button05"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, Sample3_7_Activity!</string>
<string name="app_name">Sample2_2</string>
</resources>

View File

@@ -0,0 +1,112 @@
package com.bn.pp2;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Sample2_2_Activity extends Activity {
MediaPlayer mp; // 声明MediaPlayer的引用
AudioManager am; // 声明AudioManager的引用
private int maxVolume; // 最大音量值
private int currVolume; // 当前音量值
private int stepVolume; // 每次调整的音量幅度
@Override
public void onCreate(Bundle savedInstanceState) // 重写onCreate方法
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // 设置layout
mp = new MediaPlayer(); // 创建MediaPlayer实例对象
try {
mp.setDataSource("/sdcard/gsls.mp3"); // 为MediaPlayer设置要播放文件资源
mp.prepare(); // MediaPlayer进行缓冲准备
}
catch (Exception e) {
e.printStackTrace();
}
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); // 获取AudioManager对象引用
// 获取最大音乐音量
maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
// 每次调整的音量大概为最大音量的1/6
stepVolume = maxVolume / 6;
Button bstart = (Button) this.findViewById(R.id.Button01); // 获取开始按钮
bstart.setOnClickListener // 为开始按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start(); // 调用MediaPlayer的start方法来播放音乐
Toast.makeText(getBaseContext(), "开始播放'高山流水曲'",
Toast.LENGTH_LONG).show();
}
});
Button bpause = (Button) this.findViewById(R.id.Button02); // 获取暂停按钮
bpause.setOnClickListener // 为暂停按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause(); // 调用MediaPlayer的pause方法暂停播放音乐
Toast.makeText(getBaseContext(), "暂停播放'高山流水曲'",
Toast.LENGTH_LONG).show();
}
});
Button bstop = (Button) this.findViewById(R.id.Button03); // 获取停止按钮
bstop.setOnClickListener // 为停止按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop(); // 调用MediaPlayer的stop方法停止播放音乐
try {
mp.prepare();//进入准备状态
} catch (IllegalStateException e) {//捕获异常
e.printStackTrace();
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "停止播放'高山流水曲'",
Toast.LENGTH_LONG).show();
}
});
Button bUp = (Button) this.findViewById(R.id.Button04); // 获取增大音量按钮
bUp.setOnClickListener // 为增大音量按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
// 获取当前音量
currVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
//增加音量,但不超过最大音量值
int tmpVolume = currVolume + stepVolume; //临时音量
currVolume = tmpVolume < maxVolume ? tmpVolume:maxVolume;
am.setStreamVolume(AudioManager.STREAM_MUSIC, currVolume,
AudioManager.FLAG_PLAY_SOUND);
Toast.makeText(getBaseContext(), "增大音量",
Toast.LENGTH_SHORT).show();
}
});
Button bDown = (Button) this.findViewById(R.id.Button05); // 获取减小音量按钮
bDown.setOnClickListener // 为减小音量按钮添加监听器
(new OnClickListener() {
@Override
public void onClick(View v) {
// 获取当前音量
currVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
//减小音量但不小于0
int tmpVolume = currVolume - stepVolume; //临时音量
currVolume = tmpVolume > 0 ? tmpVolume:0;
am.setStreamVolume(AudioManager.STREAM_MUSIC, currVolume,
AudioManager.FLAG_PLAY_SOUND);
Toast.makeText(getBaseContext(), "减小音量",
Toast.LENGTH_SHORT).show();
}
});
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>Sample2_3</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,12 @@
#Fri Jul 01 08:01:10 CST 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.6

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" package="com.bn.pp3">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Sample2_3_Activity"
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>
</manifest>

Some files were not shown because too many files have changed in this diff Show More