Network sharing android phone

Взаимодействие Android-устройств в локальной сети

Предположим, мы пишем игру для Android, которая подразумевает некое сетевое взаимодействие между устройствами. Причем наши устройства находятся в одной сети и мы хотим, чтобы взаимодействие между ними осуществлялось быстро, а значит вариант с обменом данными через интернет нам не подходит. Ах да, еще одна маленькая ложка дегтя — мы хотим охватить максимально возможную аудиторию, для чего нам необходимо поддерживать Android 2.3.
Что же нам делать? Давайте поговорим об этом, а заодно рассмотрим относительно новые возможности Android SDK для соединения двух и более устройств.

О чем это и для кого это?

Как-то раз, уйдя с предыдущего места работы и погрузившись в заслуженный отдых, я принялся писать сетевую игру, в которую могут играть люди, находящиеся в одной локальной сети. И сразу же столкнулся с тем, что для нормального функционирования подобной игры нам мало соорудить сетевое взаимодействие — нам нужно сделать нормальное и быстрое обнаружение устройств в сети. Собственно, в данной статье я поделюсь своим опытом в реализации решения для данной задачи.
Сразу оговорюсь, что статья предназначена в большей мере для тех, кто имеет опыт Android-разработки, написал несколько приложений и хочет расширить свой кругозор, а также улучшить профессиональные навыки.

Какие возможные способы решения существуют?

  1. Android Network Service Discovery. Простой и эффективный способ обнаружения устройств. На Android Developer есть пошаговое руководство по подключению NSD, есть пример NsdChat, который можно скачать там же. Но есть один существенный минус — данный метод поддерживается только начиная с API Level 16, то есть с Android 4.1 Jelly Bean;
  2. Второе решение, предлагаемое нам на сайте Android Developer — Wi-Fi Peer-to-Peer. Проблема этого метода та же самая — поддерживается он только начиная с API Level 16;
  3. Есть странное решение, которое предлагается некоторыми программистами на Stack Overflow — самостоятельно сканировать локальную сеть на предмет наличия сервера. То есть проходить по всем адресам сети. Это уже сейчас звучит как странный велосипед, а теперь представьте, что порт нашего сервера назначается автоматически. Таким образом, сканирование даже самую небольшой сети становится достаточно долгой и трудоемкой задачей;
  4. Наконец, мы можем обратить внимание на Java-библиотеки и написать что-нибудь с их использованием. Например, JmDNS.

Последний способ выглядит вполне адекватным и, кажется, может обеспечить нас требуемой скоростью и удобством обнаружения устройств в сети для конечного пользователя.

Я вооружился JmDNS и решил попробовать соорудить несколько классов, которые по максимуму упростят написание описанных выше приложений. Но для начала пришлось немного повырезать дубликаты .class-файлов из jar-пакета JmDNS (проблема описана здесь):

Далее я взял исходный код NsdChat с Android Developer и изменил его служебный класс, который отвечает за инициализацию сокетов и организацию сетевого взаимодействия. Также я написал wrapper для JmDNS

Здесь размещены 4 основные функции для работы Network Discovery:

  1. startServer для создания сервера и регистрации соответствующего сервиса в локальной сети;
  2. findServers для поиска серверов;
  3. reset для окончания работы с Network Discovery и последующего освобождения ресурсов;
  4. wifiLock для запроса блокировки Wi-Fi.

В завершении я написал универсальный класс ConnectionWrapper для полноценной организации обнаружения, а также обмена сообщениями в локальной сети. Таким образом, создание сервера в конечном приложении выглядит следующим образом:

А вот и mServerHandler, использующийся для приема и обработки сообщений:

Отправка сообщений еще проще:

И, наконец, метод для обнаружения и подключения к серверу:

Как видите, все очень просто. А главное, все это работает в любой версии Android для максимум двух устройств. Но сделать так, чтобы это работало для условно неограниченного числа устройств очень легко, и очевидное решение придет к вам почти сразу после детального изучения класса Connection. Пусть это будет в качестве домашнего задания.
Ах, да, весь код доступен для изучения и использования всеми желающими в моем репозитории на GitHub.. И, конечно, не исключаю то, что некоторые вещи можно сделать лучше и проще, поэтому не стесняйтесь форкать и делать pull request’ы.

Источник

How to Share Files Between Android and Windows on Your Network

With smartphones becoming a near-essential part of everyday life, you may find yourself in moments where you want to transfer files between an Android device and your Windows machine. Fortunately, it’s very easy to achieve this these days with a number of good third-party apps (as well as onboard Windows methods, to an extent) here to help.

Читайте также:  Android studio google maps построение маршрута

Here we cover the best ways to move files from Android to Windows and vice versa.

Also read: How to Share Files Between Android and Ubuntu on Your Network

Share Android Files with Windows

It’s worth noting that there are plenty of ways to perform this transfer. Bluetooth is useful, as is plugging in a cable between your PC and your phone. However, this tutorial focuses on how to transfer over your Wi-Fi network. Even with these restrictions, the competition is pretty tight. We’re focusing on two apps to transfer files between Android and Windows 10: Your Phone and Sweech.

Your Phone App

For a couple of years now, Windows has had the “Phone companion” feature. It used to be pretty threadbare and still doesn’t just give you full access to everything that’s on your phone, but certainly does the job of managing and moving Android photos through Windows 10, as well as reading, sending and deleting messages.

On your Android device, you need to get the “Your Phone Companion” app, while on Windows, the “Your Phone” app should already be on your PC. You can find it by searching for “your phone” through a Start menu search. (If it’s not there, you can download Your Phone from the Microsoft Store.)

Once you have both of these apps on their respective devices, open “Your Phone” on your PC, making sure that your phone and PC are connected to the same network.

Follow the instructions to connect your devices, then once you’re in the app, click the “Photos” icon in the pane on the left to look at all the images on your phone.

From here, you can copy-paste images to your PC, open them in a desktop app, or even drag and drop them straight onto your desktop! Simple.

Sweech App

The other app we’re focusing on is Sweech, because it’s very quick to set up; you can be transferring files within one to two minutes of downloading it!

When you download Sweech, press the large play button that appears and give the app permission to access your files. Sweech will show you a local IP address and port.

Type it into the web browser on your PC, hit Enter, and you’ll see your phone’s file system.

You can browse your phone as if it were a folder on your PC. This includes dragging files from your phone onto your PC, as well as putting files into folders on your phone. Once you’re done, tap the Stop button on the app to shut off the file transfer.

Every time you use Sweech, it will use the same IP address and port. As such, if you don’t want to keep typing in the address when you use Sweech, you can bookmark the page for quick access.

You can use the shortcuts on the left to filter content by type. You can even send data to your phone’s clipboard from your PC. Just type what you want on it, then click the blue clipboard icon to transfer it to the phone.

Also read: How to Install Google Play Store on Windows 11

How to Share Windows Files with Android

Accessing Windows folders on Android is a little trickier. First, you need to make the file or folder accessible by outside devices.

Making a File or Folder Public

The easy way to do this is to move or copy the files over to your Windows Public folder. Typically, this is located at “C:\Users\Public”. This folder is special because it’s automatically set up to allow other users on your network to access it.

If you want to share a folder without moving it to Public, you can set it up as if it were in the Public folder. To do this, right-click the file or folder you want to share, then click Properties.

Go to the Sharing tab, then click Share.

On the drop-down menu, select “Everyone,” then click Add. Click on Share at the bottom right.

By default, you’ll need your user credentials to access your PC’s public folders from outside. If you’d rather not enter them every time and trust all the devices on your network, you can instead disable the requirement and allow guests to see your public files.

To do this, type “advanced sharing” in the Start menu and select the option that appears.

Scroll down to the “All Networks” category – you may need to expand it. In this category, find “Turn off password-protected sharing” and click it, then click Save Changes.

Читайте также:  Odin андроид что это такое

Now you can access your public files without logging in. Be sure to turn this back on if you don’t want others on your network snooping on your files!

Also read: How to View Shared Files and Folders in Windows 10

Accessing the Files on Android

Now it’s time to get access to those files. You’ll need a file explorer that has LAN capabilities so that it can access your PC.

If you have an app of choice, use that. For this article, however, we are using FE File Explorer. We chose this app because it makes it easy to connect to your PC, whether you’re using an account or a guest login.

When you boot up FE File Explorer, tap the Plus button at the bottom right.

Here, you can enter the network details of your PC. If you’re on the same Wi-Fi network as your PC, you need not bother – just scroll to the bottom and find your PC in the neighborhood section.

The app will ask you if you want to log in to your PC or use a guest account. If you kept password-protected sharing on, select the top option and log in. If you turned it off, select the guest option.

Once done, you should now be able to navigate your PC’s public folders. Navigate to the files you want to download, then either tap the three dots next to a single file to see all the actions you can perform or hold-press a file to select multiple files to download or move.

As you can see, it is quite easy to transfer files between Android and Windows 10. If you are using Mac, you can make use of OpenMTP to transfer files from Android to Mac. You can even transfer files from your Android phone to your Smart TV.

Also read: How to Connect Two Computers Using a LAN Cable in Windows 10

Remember, there’s a lot more you can do if you have a Windows PC and an Android phone. For starters, you can send text messages from your desktop, run Android on your PC, and also install Windows 10 from Android.

Never Miss Out

Receive updates of our latest tutorials.

Content Manager at Make Tech Easier. Enjoys Android, Windows, and tinkering with retro console emulation to breaking point.

Источник

How to Share an Android Internet Connection with Wi-Fi Hotspot or USB Tethering

Nearly every Android smartphone can share it’s cellular data connections and turn itself into an internet hotspot, an infinitely valuable feature that lets you connect Macs, PC’s, iPad, or Nexus tablets get online through the cell connection. Of course the iPhone has the Hotspot ability too, but we’re going to focus on getting this feature working with Android this time around, and we’ll also show how to get USB tethering working between Android and Mac OS X too, which, unlike Windows, is not a supported option by default on the Mac.

Keep in mind that wi-fi hotspot and internet tethering may be an additional fee service through your cellular carrier, and each data plan differs as to whether tethering is included in the standard bandwidth allocation or if it’s available at an additional cost. Since all carriers handle personal hotspot differently, the billing situation is up to you to figure out on your own, and if you don’t see any hotspot options on your phone it’s probably because you haven’t paid for the service or your carrier doesn’t offer it. It’s also worth pointing out that, despite the incredible conveniences of hotspot features, it’s very easy to use tons of bandwidth once you connect a computer to a smartphones internet connection, and thus you should learn some simple tips to reduce data usage any time a Mac or PC has been tethered to a smartphones cell plan.

How to Enable Wi-Fi Hotspot on an Android Smartphone

Setting up wireless hotspots in Android is super easy, but it’s actually slightly different on various carriers. Why this is different is not entirely clear to me, but it may have to do with certain carriers decisions on whether or not to offer hotspot as a standard feature, or as an added data plan feature that costs an additional fee. Nonetheless, we’ll show you how to enable it on AT&T, T-Mobile, Verizon, Sprint, and, theoretically at least, any other GSM or CDMA carrier.

Android Hotspot Setup with AT&T & T-Mobile

This should also be the same for AT&T, T-Mobile and any other GSM cellular network:

  • On the Android, open “Settings”, then go to Wireless & Networks
  • Choose “More” then select “Tethering and portable hotspot”
  • Choose “Portable Wi-Fi hotspot” to enable the connection sharing
Читайте также:  Port from ios to android

If you’ve never used it before you can select a password, share name, and other configuration details. Otherwise specific hotspot configuration is accessed through “Configure Wi-Fi hotspot” option under the “Tethering & portable hotspot” menu.

Now on the Mac (or iPad, or PC), you just need to join the Android hotspot network from the Wi-Fi menu, and you’ll be online.

Configuring Mobile Hotspot with an Android on Verizon

Verizon and some other CDMA networks have a slightly different approach to enabling the personal hotspot on Android phones:

  • Go to Settings, then choose “More Settings” and go to “Wireless and networks”
  • Flip “Mobile hotspot” to ON

With hotspot toggled on, you can now join the Android network from the Wi-Fi connection menus in OS X, iOS, Windows, or whatever else you’re trying to connect to the internet.

Again, why this is different is not entirely clear, but one of the two methods above should work on virtually any Android phone running 4.0 or newer. If for some reason the above options are not available, or tethering is not working after you’ve gone through the setup process, it may be a limitation from your cellular provider that requires the feature be added to your data plan before it becomes usable.

How to Set Up USB Internet Tethering from Android to Mac OS X

Windows supports USB tethering from Android devices immediately, but that’s not the case with Macs. Curiously, there is no native OS X support for Android-to-Mac USB tethering, but the good new is that it’s very easy to add with the help of a free kernel extension called HoRNDIS. You can think of kernel extensions (kexts) as drivers, and to get tethering working you will need to install one yourself:

  • Download the Horndis package (free) and install it on the Mac
  • Turn Wi-Fi OFF on the Mac by pulling down the menu and choosing “Turn Wi-Fi Off” – this is not necessary but makes the setup easier to determine when things are working or not
  • Connect the Android to the Mac via USB cable

After the Android phone has been connected to the Mac, you need to enable USB tethering on the device itself. This can vary slightly per Android version, but it should follow the same basic steps as those described:

  • Open Settings on the Android phone, and go to “Connections” and to “More”, choosing “Tethering & Portable Hotspot”
  • Enable “USB tethering” at this menu, and within a moment or two the internet connection should now be shared through USB

At this point, the Mac should automatically detect the Android phone and set it as the primary internet connection. You can confirm this by trying to use the internet, or by going to  > System Preferences > Network and look for the name of the Android device in the connection list. If you turned off wi-fi and are using the USB tethering it will have a icon next to it and say “Connected”, and you’ll find the IP address, DNS, and router info is all set.

If for some reason the package installer fails, you can install the kext using the traditional manual installation method described here, though it’s a bit more advanced. Likewise, you can uninstall the kext that way, and if you’re not certain if you have the extension installed at all, just use the ‘kextstat’ command to list every single kernel extension in OS X.

Wi-Fi Hotspot vs USB Tethering

Wi-Fi hotspot is obviously much easier to use and to set up, but some cell providers limit how many computers or devices can connect to an individual hotspot. That’s where USB tethering offers a huge advantage, because you can tether a Mac to the Android smartphone to use it’s internet connection, and then use internet sharing on the Mac to have the Macintosh turn into it’s very own wireless hotspot. This then broadcasts it’s own signal but routes it through a single MAC address, allowing a potentially infinite number of machines to connect to the tethered connection without being detected by a cellular provider. Cool eh?

Also, some people swear that USB tethering is more reliable than wireless tethering, though in our own testing we haven’t had issues with any wifi hotspot feature that doesn’t relate directly to the overall cellular connection strength, but your experience may vary here. Thus, use whatever works for your situation, which in most cases will probably be the simple wi-fi hotspot option.

Источник

Оцените статью