15
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android 5.0/Lollipopでインターネット接続していないWi-Fiポインタに接続する

Last updated at Posted at 2015-01-16

Android 5.0/Lollipopの新機能によって、インターネット接続していないWi-Fiポインタに接続しても、モバイルデータ通信に切り替わってしまうようになりました。
→参考:Android 5.0(Lollipop)の機能紹介 : Wi-Fiでインターネットにアクセスできない場合はモバイルデータ通信に自動的に切り替える機能が追加 | ガジェット通信

やりかた

以下のようにすることで、インターネット接続していないWi-Fiポインタに接続することができます。

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] allNetwork = cm.getAllNetworks();
SocketFactory socketFactory = SocketFactory.getDefault();
for (Network network : allNetwork) {
	NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
	if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
		// SocketFactoryの取得
		socketFactory = network.getSocketFactory();
	}
}
// Socketの生成
Socket socket = socketFactory.createSocket(IP_ADDRESS, PORT);

ちなみに

以下の方法でも接続できますが、requestNetworkを実行するためにCHANGE_NETWORK_STATEのパーミッションが必要となります。
→参考:Android 5.0 APIs | Android Developers

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
	@Override
	public void onAvailable(Network network) {
		// 接続されたときに呼ばれる
		super.onAvailable(network);
		// SocketFactoryの取得
		SocketFactory socketFactory = socketFactory = network.getSocketFactory();
		// Socketの生成
		Socket socket = socketFactory.createSocket(IP_ADDRESS, PORT);
	}

	@Override
	public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
		super.onCapabilitiesChanged(network, networkCapabilities);
	}

	@Override
	public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
		super.onLinkPropertiesChanged(network, linkProperties);
	}

	@Override
	public void onLosing(Network network, int maxMsToLive) {
		super.onLosing(network, maxMsToLive);
	}

	@Override
	public void onLost(Network network) {
		super.onLost(network);
	}
});
15
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?