android執行緒實現:實時顯示所連線的wifi訊號強度(程式碼帶註釋)
阿新 • • 發佈:2019-01-03
首先:AndroidManifest.xml檔案中加一行:獲取許可權
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
layout.xml檔案中的程式碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <!-- <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" /> --> <!-- 新增一個TextView --> <TextView android:id="@+id/tvwifi" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textColor="@android:color/black" android:textSize="36sp" /> </LinearLayout> <!-- LinearLaryout佈局 -->
MainActivity的程式碼:
package com.example.wifithread; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.Menu; import android.widget.TextView; import android.annotation.SuppressLint; public class MainActivity extends Activity { private WifiManager wm; //WifiManager在包 android.net.wifi.WifiManager中 private WifiInfo wi; // WifiInfo在包android.net.wifi.WifiInfo中 private int strength; //訊號強度 private TextView tvwifi; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvwifi = (TextView) findViewById(R.id.tvwifi);//關聯TextView,方便修改TextView的內容 new TvThread().start(); } class TvThread extends Thread{ @Override public void run(){ do{ try{ Thread.sleep(1000); Message msg = new Message(); msg.what = 1;//what,int型別,未定義的訊息,以便接收訊息者可以鑑定訊息是關於什麼的。每個控制代碼都有自己的訊息名稱空間,不必擔心衝突 mHandler.sendMessage(msg); } catch (InterruptedException e){ e.printStackTrace(); } }while (true); } } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch(msg.what){ case 1: wm = (WifiManager) getSystemService(WIFI_SERVICE); //getSystemService(String),通過名字來返回系統級服務的控制代碼。返回型別隨要求變化。 //使用getSystemService(String)來取回WifiManager然後處理wifi接入, wi = wm.getConnectionInfo();//getConnectionInfo返回wifi連線的動態資訊 if(wi.getBSSID() != null)//getBSSID返回基本服務集識別符號,如果未連線,返回null,否則返回MAC地址形式:XX:XX:XX:XX:XX strength = wi.getRssi();//返回接收到的目前的802.11網路的訊號強度 tvwifi.setText(((Integer) strength).toString()); break; default: break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
效果圖: