Running ubuntu and android

How to install a Linux desktop on your Android device

One of the things I love most about being a freelance writer and independent app developer is the amount of freedom it gives me to live and work as I like. Often this means travelling and working on the move. Some of my favorite memories involve typing away in bars in foreign countries while sipping beer and soaking up the atmosphere. Other times I find myself working in coffee shops around London or Oxford. It’s ace.

The only problem is the tech. While there are plenty of great hybrid Windows tablets out there like the Surface Pro (my daily driver), the issue is that these can’t fit into my pocket. So, if I’m meeting friends in London for drinks and I fancy working with a view of Big Ben, I have to take a man-bag with me and then carry it around the bars and clubs worrying constantly about it getting stolen or damaged. If I want to work on my upcoming trip to Berlin, I’ll need to take my laptop with me and use up pretty much all my hand-luggage.

What I really want is for my phone to be fully capable of replacing my laptop. It’s powerful enough for sure and the 5.1” screen is large enough for still-decent eyesight. The problem is the software.

I love Android, but the multitasking features are still relatively tame. Phones with Android N and up have multiscreen functionality but really I need a full desktop environment to get properly into my workflow. I want to view a browser to do research while editing a proper docx file. I want to be able to browse files and drag and drop them into WordPress.

And that’s the real genius of Android because it actually allows you to do all that. Android is so open and so flexible that there are multiple ways you can get a full desktop environment up and running on your smartphone. And that includes an option to install the full desktop version Ubuntu! That requires root but not every option does. Read on…

A bunch of ways to get a desktop environment running on your Android phone (no root)

Crossover for Android

If you are one of the fortunate few to have an Intel powered smartphone, such as the Zenfone 2 or the Lenovo K900, then you will be able to install and run an app called ‘Crossover’. This is essentially an app that lets you install and run Windows software directly such as Steam, Microsoft Office and more at native speeds. The programs run in windows too that can be dragged around and resized just as though they were running on a desktop PC!

Not all software works though and unfortunately the fact that you need an Intel processor is going to be a limiting factor for most users.

Debian No Root

Debian No Root will install a ‘flavor’ of Debian called ‘Jessie’, or rather it will install a ‘compatibility layer’ allowing you to run Debian software in a desktop environment. The distro comes with a terminal, allowing you to install additional software. Just type sudo apt-get install iceweasel to get a browser based on Firefox up and running for example.

There are compatibility issues here once again though. Any phone running an Android version older than 4.4 won’t allow you to uninstall and then reinstall. More concerning is that you won’t be able to install any software on versions 6.0 and upwards. This is because the developer doesn’t have a new phone to test on and hasn’t been able to fix the bugs as a result…

It’s frustrating because for those phones that can run Debian No Root, this is a pretty decent option. It’s a little slow but other than that, this is the dream of Linux without root!

Читайте также:  Astro file manager astro для андроид

Limbo PC Emulator

Yes, you read right! There is a PC emulator called Limbo that runs on Android devices and is powerful enough to let you get Windows up and running. I’ve not had any luck with it myself and it seems to be a rather laborious process that results in something that’s pretty slow. So, my advice is to skip this option. Still though, if you are the kind of person to go through the entire process just so you can show off your phone running Windows… you’ll find the instructions here.

Heck, if you want to go the emulator route there’s nothing stopping you from installing Windows 95 through DosBox. Just don’t expect to do anything much with it…

Multitasking Apps

There are a bunch of apps out there that seek to emulate a desktop environment. My favorite is Multiscreen Multitasking seeing as I made it… This is an app that builds lots of small utilities into a single app and then puts them inside draggable windows. Basically, it just lets you open up webviews and edit texts and then drag them around. Though I did make a file manager and include the option to load up widgets and use them like mini apps inside windows. You can also do some other stuff, like open the source of a website or save it as an editable image file and draw on it. I’ll be honest though: Multiscreen Multitasking is old now. My coding abilities have come a long way since then and it’s pretty janky. I actually made this in Basic4Android! One day, I intend on rebuilding this app with full Docx support, sheets and a nicer UI. To be clear though, I’m not recommending you download it as it is right now.

Frustratingly, another developer has actually done the same thing slightly better with Leena Desktop UI. This is the very same concept but it is a bit more attractive and the browser supports Google Drive and Google Docs – so you can actually get some work done! It’s a launcher too, so you can use it to launch your regular apps. Sentio is similar and there are other options out there… but I still did it first! And finally you have the various floating apps options, such as the well-named ‘Floating Apps’. To be honest though, floating apps tend to be a little fiddly to use and no replacement for a true desktop.

And the rest…

As you can see then, there are plenty of options for getting some kind of desktop environment up and running on your device without having to root. Of course, if you have the new Samsung S8 then you can try using DeX – though that requires an external monitor (until someone figures out a hack at least). Another option is to stream your desktop PC using software like Splashtop Remote. This relies on your PC being on and your connection being strong however. Either way, there are plenty of options and you should be able to find something that works for you with minimum compromises.

Just be aware of some of the scams out there – options like ‘Change My Software’ do not work. If you’re ever unsure, just see what the XDA Forums make of it.

All this pales in comparison though to installing true desktop Ubuntu on your Android device! So, without further ado…

How to install Ubuntu and other versions of Linux on your Android device

For this to work you will need a rooted Android device. Rooting your device is usually a fairly simple process but note that it varies from device to device, so I can’t give you a walkthrough here.

Once that’s done, you’ll need three apps:

First install BusyBox. BusyBox gives your phone access to Linux commands that it wouldn’t otherwise have and is required for a number of root apps to work. Once you’ve installed it though, you don’t need to worry about it again.

Open up Linux Deploy and make sure it has root access. Now hit the small download button on the top or bottom right of the screen. This will bring you to the options menu. Most of the settings in here can be left as they are but this is where you’ll select your Linux distribution. Everything is here from Debian and Ubuntu to Kali Linux, Gentoo, Fedora and more. Picking the suite will change the ‘flavor’ of Linux. You can try them all or you can do a little research and choose whichever you like the looks of most.

Читайте также:  Калибровка батареи через инженерное меню андроид смартфона

Down the bottom you can also choose which Desktop environment you like, which will change the look and feel of the app. Tick ‘Enable’ under GUI to ensure you have a graphical interface to work with and check out the GUI Settings just below to change things like the resolution. For my Galaxy S6 Edge Plus I find that 1024×576 works best but you can toy around with this later. Set your user name to ‘root’ to give yourself privileged access and make a note of the password or change it to something more memorable.

Now click the menu that looks like three dots and choose ‘Install’. This will take a little while but will install the entire Linux distro on your device. Click the ‘Start’ button to run it in ‘chroot’ – essentially a small sub-compartment on your device.

Finally, you’ll use VNC Viewer in order to actually view the GUI. Load it up and set the address to ‘localhost:5900’. Then enter the password that you set earlier.

And with that as long as your version of Linus is running you’ll be golden! Now if you want start adding more software head into the Terminal and type:

  • Apt-get install libreoffice – For LibreOffice
  • Apt-get install iceweasel For Firefox
  • Apt-get install idle – For Python Idle
  • Apt-get install gimp – For GIMP
  • Apt-get install nautilus-dropbox – For DropBox
  • Apt-get install software-center – For an ‘app store’, although this wouldn’t run on my distro

There are plenty more but that should be enough to get you started. You should also run ‘apt-get update’ at some point to ensure everything is up-to-date.

Other than that, grab yourself a Bluetooth keyboard and mouse and get to work! Be sure to let us know how you get on in the comments or if you have discovered any other methods of getting a full desktop environment up and running on your phone.

Источник

Изучаем принципы взаимодействия Ubuntu Touch и Android


Привет, хабр.

Пару месяцев назад я занимался портированием Ubuntu Touch на платформу Allwinner A10 ,
в процессе делал заметки себе на память. Сейчас, на мой взгляд, они всё ещё актуальны, пока Ubuntu Touch окончательно не переехала на свой графический сервер Mir и так далее.

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

Стиль изложения далёк от технического, но если вы не против, то
приглашаю под кат.

Введение

Что такое libhybris

libhybris — прослойка, позволяющая подгружать в Glibc userspace библиотеки из Bionic userspace, на лету заменяя некоторые символы вариантами из Glibc. Проще говоря, данное решение позволяет использовать проприетарные библиотеки для Android в Linux-пространстве. Наибóльшая польза, конечно же, в возможности использовать проприетарные GPU-драйвера, собранные производителем только под Android.

Что такое surfaceflinger

surfaceflinger — нативный сервис андроида, композитный менеджер графических слоёв.

Ubuntu Touch

Ubuntu Touch Developer Preview сама по себе основана на Android, заимствует необходимые сервисы для работы с железом. Общий обзор зависимости можно почитать здесь — Ubuntu Touch Porting или в заметке на OpenNet.

В качестве базовой операционной системы используется обычный Android JB 4.2 , а точнее CyagenMod-10.1 (репозиторий подпроектов CM — phablet.ubuntu.com/gitweb). Из него удалено всё что связано с dalvik и java — оставлена только нативная часть, состоящая из системных сервисов и HAL . При желании можно использовать AOSP 4.1 , но будьте готовы к адаптации под нативное API от 4.1, оно не покрыто никакой документацией и тем более спецификацией и меняется от релиза к релизу.

Компоненты UT располагаются в chroot , используется самописная утилита uchroot, отрывок:

Читайте также:  Восстановление microsd для андроид

Для взаимодействия Android-окружения и chroot-окружения Ubuntu задействован механизм libhybris .

Компоненты Ubuntu Touch

phablet-team.
Нас интересуют следующие два компонента, отвечающие за работу платформы на Android устройствах:

  • platform-api
  • qtubuntu

Скачаем последнюю версию исходников:

Ubuntu Platform API

Ubuntu platform API — низкоуровневый API для выполнения базовых операций с использованием возможностей платформы (Android).

Примеры методов:

  • ubuntu_application_ui_show_surface
  • ubuntu_application_ui_hide_surface
  • ubuntu_application_ui_move_surface_to
  • ubuntu_application_ui_resize_surface_to

Из файла документации doc/mainpage.md узнаём, что дерево исходников platform-api можно разбить на две части:

  • include — абстрактная декларация platform API
  • android — реализация platform API под Android (я бы уточнил — под Android 4.2)

И то единственное, на что может полагаться сторонний разработчик при работе с этим API — это заголовки из
директории includes/ubuntu/application, а всё остальное предполагает изменяться со временем.

Из файла debian/control узнаём, что:

Ага, значит, судя по android/hybris/Android.mk, реализация platform API собирается в виде библотеки libubuntu_application_api с линковкой с нативными либами андроида и помещается в android userspace:

Без внимания осталась директория platform-api/src/android, рассмотрим её в деталях. Судя по наличию файла CMakeLists.txt , сборка идёт уже для glibc.

Есть один-единственный файл с кодом — ubuntu_application_api.cpp, заглянув в которой мы увидим:
— использование процедур libhybris для динамической загрузки символов из shared-либы из android userspace.

— нехитрый мост для подгрузки символов из libubuntu_application_api.so , которая ладит с нативными сервисами андроида, и которую мы совсем недавно мысленно «собрали» с помощью android/hybris/Android.mk.

— куча обёрток для символов API, реализованных в libubuntu_application_api.so .

Итак, во избежание путаницы:

  • libubuntu_application_api.so — библиотека под bionic, живёт в android userspace;
  • libubuntu_application_api.so — библиотека под glibc, живёт в linux userpace (chroot), грузит символы из первой через libhybris.

Разработчики решили уменьшить энтропию вселенной путём создания одноимённых библиотек.
Если посмотреть их дебаты по поводу именования компонентов merge-153874 discussion, то уши вянут.

Ubuntu Application Manager

В platform-api/android/hybris помимо реализации Ubuntu platform API находятся исходники ubuntuappmanager — сервиса приложений Ubuntu, он живёт в android userspace и, судя по Android.mk, активно использует libubuntu_application_api и общается через Binder IPC с сервисами андроида.

Решает кучу задач управления приложениями и сессиями, быстрый взгляд на default_application_manager.h:

QtUbuntu

Разбираемся с частью UT, отвечающей за взаимодействие между Ubuntu platform API и Qt/QML приложениями.

Если вы не знакомы с Qt Platform Abstraction, то, в кратце, это возможность абстрагироваться от платформы, на которой запускаются приложения Qt с помощью специально написанных QPA-плагинов.

В QPA-плагине реализуются базовые методы вроде createPlatformWindow , а затем Qt приложение, когда захочет создать окошко, использует символ createPlatformWindow из плагина абстракции и в ус не дует, куда оно там дальше пошло.

В данном случае мы будем иметь дело с QPA плагином для работы с Ubuntu application API.

Судя по содержимому ubuntu.pro, платформа линкуется с glibc-версией libubuntu_application_api.so
Обратим внимание на следующие вызовы методов из набора platform API, использованные в integration.cc и window.cc:

Теперь понятно, что когда наше Qt приложение захочет создать окошко, то оно вызовет метод из QPA платформы qubuntu — QUbuntuIntegration::createPlatformWindow из файла integration.cc:

Заглядывая в конструктор QUbuntuWindow в файле window.cc, находим вызов метода QUbuntuWindow::createWindow() :

Это крайне урезанный код, но суть ясна — делаются вызовы к Ubuntu platform API , которое у нас реализовано в glibc-версии libubuntu_application_api.so , которая, на самом деле, является мостом к bionic-версии libubuntu_application_api.so , код которой лежит в platform-api/android.

Нам осталось открыть матрёшку и найти, как же реализованы ubuntu::application::ui::Session и, соответственно, ubuntu::application::ui::Surface . А реализованы они в этом файле — ubuntu_application_api_for_hybris.cpp:

Перематываем, находим UbuntuSurface :

Получаем некий объект типа android::SurfaceControl , который является результатом вызова android::SurfaceComposerClient()->createSurface() .
Через него проходят все обращения к android::SurfaceComposerClient (frameworks/native/libs/gui/Surface.cpp), такие как: изменение размеров, перемещение, изменение порядка слоёв и так далее.

Возвращаясь назад по цепочке, понимаем, что же на самом деле происходит, когда мы запускаем очередное Qt приложение с QPA платформой Ubuntu.

Заключение

На этом моменте я вынужден себя остановить, поскольку, на мой взгляд, рассмотренный принцип взаимодействия Ubuntu Touch и Android является самодостаточным. Дальнейшие рассуждения могут идти уже в отрыве от всего вышеописанного. Нерасмотренными остались вопросы взаимодействия qmlscene и ubuntuappmanager , принцип контроля ввода с помощью сервисов SurfaceFlinger и InputDispatcher и другие вопросы из уголков этой простороной темы. Но это уже совсем другая история.

Через неделю приедет телефон на Firefox OS, распотрошу его…

Источник

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