1. 程式人生 > >Android監控WIFI和GSM狀態並繪製網路強度

Android監控WIFI和GSM狀態並繪製網路強度

在實際工作中,常常遇到APP顯示網路強度的需求。

使用過程中涉及的應用許可權如下:

    <!--wifi及網路狀態-->
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

一、網路強度分為二個部分:

    1、手機網路GSM(2G/3G等)

        GSM需要註冊PhoneStateListener監聽器,通過監聽網路改變,獲取手機當前網路的強度。

        /* Update the listener, and start it */
        MyListener = new MyPhoneStateListener();

        Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);
        Tel.listen(MyListener , PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

    /* Start the PhoneState listener */
    private class MyPhoneStateListener extends PhoneStateListener
    {
      /* Get the Signal strength from the provider,
       * each tiome there is an update
       *從得到的訊號強度,每個tiome供應商有更新
       */

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength)
        {
            super.onSignalStrengthsChanged(signalStrength);
            //訊號強度換算公式
            int astSignal = -113 + 2*signalStrength.getGsmSignalStrength();
            gsm.setText("GSM 訊號強度asu :" + signalStrength.getGsmSignalStrength() +"_dBm :"+astSignal);
        }

    };/* End of private Class */

    2、Wifi網路

        Wifi也可以註冊WifiManager.WIFI_STATE_CHANGED_ACTION 廣播,來獲取Wifi訊號強度。

        但該方法不及時!!該方法自行搜尋!

        若應用的及時性要求比較高的時,我推薦採用主動定時獲取的方式。本文也是使用該方法。

    private void getWifiInfo() {
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getBSSID() != null) {
            //wifi名稱
            String ssid = wifiInfo.getSSID();
            //wifi訊號強度
            int signalLevel = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 6);
            //wifi速度
            int speed = wifiInfo.getLinkSpeed();
            //wifi速度單位
            String units = WifiInfo.LINK_SPEED_UNITS;
            wifi.setText("wifi_level:"+signalLevel +"_speed:"+speed +"_units:"+units);
            wifiDrawView.setType(signalLevel);
        }
    }


二、繪製網路強度

自定義View,通過過載onDraw方法來達到繪製網路強度的圖形。本文是繪製的圖示為 手機訊號的樣式。

設定強度

    myDrawView.setType(t);
   
     public void setType(int type){
     this.type = type;
      postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //把整張畫布繪製成白色
        canvas.drawColor(0x00000000);
        Paint paint = new Paint();
        //去鋸齒
        paint.setAntiAlias(true);
        paint.setColor(Color.BLUE); //線條填充的顏色
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5); //設定線條的寬度
        Log.i(TAG,"TYPE:" + type);
        if(type <=2){
            //繪製
            paint.setColor(Color.RED);
            canvas.drawLine(dip2px(context, 2), dip2px(context, 14),
                    dip2px(context, 2), dip2px(context, 16),
                    paint);
        }else{
            paint.setColor(Color.GREEN);
            //繪製
            canvas.drawLine(dip2px(context, 2), dip2px(context, 14),
                    dip2px(context, 2), dip2px(context, 16),
                    paint);
            if (type >=3){
                canvas.drawLine(dip2px(context, 7), dip2px(context, 12),
                        dip2px(context, 7), dip2px(context, 16),
                        paint);
                canvas.drawLine(dip2px(context, 12), dip2px(context, 8),
                        dip2px(context, 12), dip2px(context, 16),
                        paint);
            }
            if (type >= 4){
                canvas.drawLine(dip2px(context, 17), dip2px(context, 4),
                        dip2px(context, 17), dip2px(context, 16),
                        paint);
            }

            if (type >=5){
                canvas.drawLine(dip2px(context, 23), dip2px(context, 0),
                        dip2px(context, 23), dip2px(context, 16),
                        paint);
            }
        }
    }



    /**
     * 根據手機的解析度從 dp 的單位 轉成為 px(畫素)
     */
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

資原始檔

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="模擬訊號" />

    <test.android.com.drawdemo.MyDrawView
        android:id="@+id/myDraw"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@id/text1"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/gsm_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myDraw"
        android:text="GSM"
        android:textColor="@color/background_floating_material_dark" />

    <TextView
        android:id="@+id/wifi_data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/gsm_data"
        android:text="wifi"
        android:textColor="@color/background_floating_material_dark" />

    <test.android.com.drawdemo.MyDrawView
        android:id="@+id/wifiDraw"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/wifi_data"
        android:layout_marginTop="10dp" />

</RelativeLayout>

執行截圖: