Get Network on android.intent.action.BOOT_COMPLETED

亡梦爱人 提交于 2020-01-16 04:26:33

问题


I've an app that has a receiver of android.intent.action.BOOT_COMPLETED and start a private VPN. But when I receive a android.intent.action.BOOT_COMPLETED the network isn't ready yet. What can I do to start a android.intent.action.BOOT_COMPLETEDand wait to have a network status? for example I can have a android.intent.action.BOOT_COMPLETED but the phone has no internet connection, or I can have a android.intent.action.BOOT_COMPLETED and 5 seconds later a internet Access.


回答1:


You could register a broadcast receiver listening on the android.net.conn.CONNECTIVITY_CHANGE action.

then check if you are connected like this:

public boolean isOnline(Context context) {

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());

}

source and more information: Broadcast receiver for checking internet connection in android app




回答2:


You can always listen to multiple items on one receiver:

<receiver android:name=".ReceiverName" >
    <intent-filter >
        <action android:name="android.net.wifi.STATE_CHANGE" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

So after boot you just wait for connectivity change and do your stuff.



来源:https://stackoverflow.com/questions/29799904/get-network-on-android-intent-action-boot-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!