close

網路功能在手機上是很重要的,許多android app都很依賴是否有網路來進行後續的行為,下述記錄如何判斷目前的手機有開啟網路功能。

首先,要先在 AndroidManifest.xml中加上網錄讀取的權限,如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="tw.idv.ken.myapplication">
    <
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:roundIcon="@mipmap/ic_launcher_round"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>

</
manifest>

 

確定後就能在程式中加上判斷網路的功能:

 

上述的15, 16行就是先取得service,再從service中取得網路狀態,然後line 18 就是判定其網路狀態。

 

部屬到手機上的圖片如下:

Screenshot_20200813-131658.png

 

Reference:

https://sites.google.com/site/chengshixuexipingtai/android/pan-duan-wang-lu

 

arrow
arrow
    全站熱搜

    葛瑞斯肯 發表在 痞客邦 留言(0) 人氣()