如何在安卓裝置中啟用藍牙?


本例演示瞭如何在安卓裝置中啟用藍牙。

步驟 1 − 在 Android Studio 中新建一個專案,轉到 File ⇒ New Project,然後填寫所有必需的詳細資訊來新建一個專案。

步驟 2 − 新增以下程式碼到 res/layout/activity_main.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>

在以上程式碼中,我們使用了一個文字檢視來顯示藍牙狀態。

步驟 3 − 新增以下程式碼到 src/MainActivity.java 中

package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;
import android.os.health.SystemHealthManager;
import android.provider.Telephony;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText("enable");
      final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
      textView.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            manager.getAdapter().enable();
         }
      });
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}

讓我們嘗試執行您的應用程式。我假設您已將您的實際安卓移動裝置連線到您的計算機。要透過安卓工作室執行該應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行  圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示預設螢幕 –

點選此處 下載專案程式碼

更新於:2019 年 7 月 30 日

384 次瀏覽

開啟你的職業

完成該課程獲得認證

開始
廣告
© . All rights reserved.