Android BLE开发总结第一篇

首先说AndroidManifest.xml文件

AndroidManifest.xml除了能声明程序中的Activities, ContentProviders,Services, 和Intent Receivers,还能指定permissions和instrumentation(安全控制和测试)

下面截取部分进行说明:

<?xml version="1.0"encoding="utf-8"?>

//定义android命名空间,使得Android中各种标准属性能在文件中使用
<manifest xmlns:android=http://schemas.android.com/apk/res/android

//指定本应用内java主程序包的包名,它也是一个应用进程的默认名称
    package="com.blue_light">
    <uses-permission
android:name="android.permission.BLUETOOTH"/>
    <uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"/>
    <application

//当allowBackup标志为true时,用户即可通过adb backup和adb restore来进行对应用数据的备份和恢复,这可能会带来一定的安全风险
        android:allowBackup="true"
       
android:icon="@mipmap/applogo"
       
android:label="@string/app_name"

//声明你的application是否愿意支持从右到左(RTL就是right-to-left)的布局。
        android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <activity
           
android:name=".WelcomeActivity"
           
android:label="@string/app_name"

//landscape:限制界面为横屏,旋转屏幕也不会改变当前状态。

//portrait:限制界面为竖屏,旋转屏幕也不会改变当前状态。
           
android:screenOrientation="portrait"
           
android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>

//指定程序的入口
                <action
android:name="android.intent.action.MAIN"/>

//指定加载该应用时运行该Activity
                <category
android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activity
           
android:name=".MainActivity"
           
android:theme="@style/AppTheme.NoActionBar"

//  android:windowSoftInputMode="adjustPan"当前窗口的内容将自动移动以便当前焦点从不被键盘覆盖和用户能总是看到输入内容的部分

// android:windowSoftInputMode="stateVisible|adjustResize" 屏幕整体上移
           
android:windowSoftInputMode="adjustPan"/>
        <service
           
android:name="com.csr.btsmart.BtSmartService"
           
android:enabled="true"

//该属性用来标示,其它应用的组件是否可以唤醒service或者和这个service进行交互:如果为false,只有同一个应用的组件或者有着同样user ID的应用可以启动这个service或者绑定这个service。
            android:exported="false"></service>
    </application>
</manifest>

下面就来分析每一个用到的源程序文件:

首先是WelcomeActivity,如果是首次进入,等待2秒后跳转到MainActivity

//读取SharedPreFerences中需要的数据,使用SharedPreFerences来记录程序启动的使用次数
//取得相应的值,如果没有该值,说明还未写入,用true作为默认值
SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
isFirstInit = preferences.getBoolean(FIRST_INIT_FLAG, true);

 

try{
        Thread.sleep(
2000);
       
intent = newIntent(WelcomeActivity.this,MainActivity.class);
   
} catch(InterruptedException e) {
        Log.e(
DEBUG_TAG,"First initfailed to start MainActivity.\n"+ e.getMessage());
       
e.printStackTrace();
        return;
   
}
WelcomeActivity.
this.startActivity(intent);
WelcomeActivity.this.finish();


SharedPreferences preferences = getSharedPreferences(WelcomeActivity.SHARED_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(WelcomeActivity.FIRST_INIT_FLAG, false); /* 提交修改 */
editor.commit();

初始化安装时,往往需要创建一些文件夹

public staticFile path1;

//在SD卡上创建一个文件夹
public static void createSDCardDir(inttype){
   
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
       
// 创建一个文件夹对象,赋值为外部存储器的目录
       
File sdcardDir =Environment.getExternalStorageDirectory();
       
//得到一个路径,内容是sdcard的文件夹路径和名字
        if(type==1){
           
path=sdcardDir.getPath()+"/Blue_Light/单开";
       
}
       
else if(type==2){
           
path=sdcardDir.getPath()+"/Blue_Light/双开";
       
}
       
else if(type==3){
           
path=sdcardDir.getPath()+"/Blue_Light/三开";
       
}
       
path1 =new File(path);

        if
(!path1.exists()) {
           
//若不存在,创建目录,可以在应用启动的时候创建
           
path1.mkdirs();
           
Log.i(TAG,"创建文件成功");
       
}
    }
   
else{
        Log.i(
TAG,"文件已存在");
   
}
}

创建数据库操作对象

Android中创建数据库有两种方法:

1.手动创建或者打开数据库

 SQLiteDatabase database =openOrCreateDatabase("myDevice.db3", MODE_PRIVATE, null);     调用openOrCreateDatabase()方法,如果有该数据库,就打开,没有就创建一个。

2.使用SQLiteOpenHelper, 然后我们再在Activity中这样使用:

//创建MyDatabaseHelper对象,创建数据库myDevice.db3指定数据库版本为1,此处使用相对路径即可,
//数据库文件自动会保存在程序的数据文件夹的databases目录下。
db = new DatabaseHelper(this,"myDevice.db3", null,1);

SQLiteOpenHelper是一个抽象的数据库操作类,首先执行的是OnCreate,这里我们可以执行创建表等动作,但该方法并没有真正创建数据库,创建数据库是在以下的情况:

SQLiteDatabasedatabase = helper.getWritableDatabase();调用getWritableDatabase()或者getReadableDatabase()时,就会真正创建数据库。创建或打开数据库后,我们就可以建表

数据库中创建四张表并插入一条默认场景数据:

//创建设备表SQL语句
private static final StringCREATE_DEVICE_TABLE_SQL ="create table device(_id integerprimary " + "key autoincrement , name,device_scene_name,device_group_name,address,mode);";
  
//创建设备表SQL语句
private static final String  CREATE_BASEDEVICE_TABLE_SQL="create tablebasedevice(_id integer primary " + "key autoincrement , address , name,mode ,scene_name);";
//创建场景表SQL语句
private static final StringCREATE_SCENE_TABLE_SQL ="create table scene(_id integerprimary " + "key autoincrement ,scene_name,scene_state);";
//创建分组表
private static final StringCREATE_GROUP_TABLE_SQL ="create table groups(_id integerprimary " + "key autoincrement ,group_scene_name,group_name);";
private static final
String INSERT_SCENE_SQL= "insert into scene values(null ,'AndroidHome','Yes');";

获取某一场景下所有设备:

/**获取某一场景下所有的设备
    */
  
public List<BaseDeviceItem>getAllDevice_Scene(String scene_name)
   {
      List<BaseDeviceItem> devices=
new ArrayList<BaseDeviceItem>();

//获取游标
     
Cursor cursor = this.getReadableDatabase().rawQuery("select * frombasedevice where scene_name=?", new String[]{scene_name});

//使用游标遍历所有数据
      while
(cursor.moveToNext()){

//使用游标获取基本信息参数,生成基本设备对象
         BaseDeviceItem device=
new BaseDeviceItem(cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
        
devices.add(device);
     
}
     
return devices;
  
}

基本设备表中添加设备:

/**
 *
基本表中添加设备
 */
public void addBaseDevice(String address,String name,String mode,String scenename)
{
   SQLiteDatabase db =
this.getWritableDatabase();
  
db.execSQL("insert into basedevicevalues(null,?,?,?,? )",
         new
Object[]{address,name,mode,scenename});
  
db.close();
}

修改基本表信息:

/**
 *
修改基本表设备名称
 */
public void updateNameBaseDevice(final String oldname,String newname,String scene)
{
   SQLiteDatabase db =
this.getWritableDatabase();
  
db.execSQL("update  basedevice "+ "set name =? where name = ? andscene_name=? ",
         new
Object[]{newname,oldname,scene});
  
db.close();
}

删除设备表中设备:

/**删除设备表中设备
 */
public void delDevice_Device(String sceneName,String groupName,String devicename)
{
   SQLiteDatabase db =
this.getWritableDatabase();
  
db.execSQL("DELETE FROM device WHEREdevice_scene_name = ? and device_group_name= ? and name=?", newString[] {sceneName,groupName,devicename });
  
db.close();
}

删除一个场景时要记得删除所有数据库表中包含该场景信息的条目。

另外添加一段Android中数据流的使用:

InputStream im = getResources().openRawResource(R.raw.smart_switchv0_3_update_1_20160325);
//加一个判断条件,改变写入到不同类型文件夹的文件,即改变im和path2的路径名
                            path2 =new File(OtaFileWriteManager.path1+ "/Smart_SwitchV0.3_update_1_20160325.img");
                            if
(!path2.exists())
                           OtaFileWriteManager.inputstreamtofile(im
,path2);

public static voidinputstreamtofile(InputStream ins,File file) {
   
try {
        OutputStream os =
new FileOutputStream(file);
        int
bytesRead = 0;
        byte
[] buffer = new byte[1024];
        
while ((bytesRead = ins.read(buffer,0, 1024))!= -1) {
           
os.write(buffer,0, bytesRead);
       
}
        os.close()
;
       
ins.close();
   
} catch(Exception e) {
        e.printStackTrace()
;
   
}
}

 

猜你喜欢

转载自blog.csdn.net/songkai320/article/details/78152133
今日推荐