- Using Scripting Languages in Android
- Placing the phone face down will disable the ringer. Turning it face up again will enable the ringer.
- Here’s another useful script, this time in Python.
- All in one script android
- All in one script android
- Kotlin DSL: Gradle scripts in Android made easy
- Let’s get started
- Is there anything left to do? 🤔
- AppConfig.kt:
- Versions.kt
- AppDependencies.kt
- settings.gradle
- settings.gradle.kts
- build.gradle
- build.gradle.kts
- Styling TextView using Kotlin DSL.
- Output:
Using Scripting Languages in Android
At launch, Java was the only officially supported programming language for building distributable APK.Android Native Development Kit (Android NDK) which will allow developers to build Android software components with C and C++ .In addition to delivering support for native code, Google is also extending Android to support popular dynamic scripting languages and Google launched the Android Scripting Environment (ASE) but now it is Open Source and Known as Scripting Layer for Android(SL4A brings scripting languages to Android by allowing you to edit and execute scripts and interactive interpreters directly on the Android device.) and allows third-party developers to build simple Android applications with perl , JRuby , Python , LUA and BeanShell .SL4A makes it possible to quickly prototype applications for Android on the device itself using high-level scripting languages. These scripts have access to many of the APIs available to full-fledged Android applications, but with a greatly simplified interface and You can embed your script in a stand alone APK.
You may ask, why write scripts instead of real Android applications? Admittedly, Android’s development environment makes life pretty easy, but you’re tied to a computer to do your work. ASE lets you develop on the device itself using high-level scripting languages to try out your idea now, in the situation where you need it, quickly. Have a look at the following example Lua script to see for yourself:
Placing the phone face down will disable the ringer. Turning it face up again will enable the ringer.
Here’s another useful script, this time in Python.
“Say chat messages aloud as they are received”
These scripts demonstrates several of the available APIs available for both Lua and Python. It is intended to be run as a service and silences the ringer when the phone is placed face down. For some scripting languages, like BeanShell, it’s possible to access Android’s Java API directly. To simplify things, ASE provides the AndroidFacade class. For other languages, like Python and Lua, the API is made available via JSON RPC calls to a proxy. Naturally this means that only the part of the API which has been wrapped by the AndroidFacade and AndroidProxy are available to cross-compiled interpreters like Python and Lua. Thankfully, both AndroidFacade and AndroidProxy are simple to extend.
Источник
All in one script android
По функционалу программы:
— При первом запуске было бы хорошо если б программа определяла свое место положение, а не C:\****
— Лучше если б папки «входящие файлы» (добавляем файлы) и «исходящие файлы» (сохраняем архив) были б созданы сразу. Ну и путь к ним сразу определился
— Заполненные параметры «пути» в закладках Файлы и Сборка — иногда сбрасываются при переходе между этими закладками
— Непонятно для чего кнопка «сохранить» в закладке Скрипт
— Сделать выбор бинарника, т.к. они не 100% универсальны
— Расширить варианты выбора скриптов
Пожелания по удобству использования:
— чтоб исключить синтаксические ошибки — ввести выделение красным отсутствие символа в команде, т.е. выделять ошибки
— на примере http://www.softportal.…ad-fisherman-big-4.gif хотелось бы.
а) список скриптов и их описание сбоку, а не в выпадающем меню
б) выделение команды одним цветом, а значения — другим (гораздо удобнее)
— сделать другую компоновку кнопок, поле скрипта и свободного места в окне программы, а именно более компактней. т.к. очень много пустого места, а при написании скрипта на экране много других окон открыто, которые не хотелось бы перекрывать.
— назвать исполняемый файл согласно названию программы (непонятно почему ACC)
— убрать из корня папки программы весь «мусор», закинуть его в отдельную папку. оставить лишь запуск программы и папки «входящие», «исходящие».
— для закладки Файлы — при нажатии кнопки «добавить» создавался бы список файлов, которые уже добавили (т.е. отображение того что в итоге будет записываться в скрипт)
Спасибо за начало разработки такой полезной программы.
Выше написал от себя пожелания, исходя из опыта работы в других программах (Notepad++, HtmlPad FisherMan). Правда еще не пробовал работу скрипта на планшете.
Также стоит Вам отписаться в теме Android update-script для привлечения людей к тестированию.
Для связывания тем — добавлю ссылку на эту тему в топик Android update-script , можно взаимно )
Новая версия, от 12-04-2014 Скачать
Версия: 1.0 BETA Android_Script_BETA.zip ( 7.3 МБ )
Добавлено:
1. Выбор бинарника. (свой бинарник пока что нельзя выбрать, но в будущем можно будет и выбирать)
2. Добавлено описание к командам и примеры.
3. На странице «Скрипт», напротив синтаксиса команды, добавлена кнопка «Добавить». Вы можете отредактировать синтаксис команды, нажав кнопку «Добавить» программа добавит строчку с вашей командой в скрипт.
4. Имя программы изменено.
Отвечаю на вопросы:
На стадии бета тестирования такого не будет, программа запоминает последний вобранный путь (после сборки), или в файле sfdata.ini вы сами можете указать пути которые вам удобны.
он подтягивается с файла sfdata.ini, после добавления файлов программа запоминает путь.
когда вы собрали апдейт, временная папка вместе с файлом скрипта удаляется, для того что-бы собрать новый апдейт, необходимо на вкладке «Скрипт» нажать «Сохранить», для того что-бы создался файл скрипта. (в будущем исправлю этот баг)
Шаблоны будут, но позже. Или вы имеете что-то другое?
на дынный момент, эта программа пишется на движке AMS, и у него нет синтексеса, если он появится добавлю синтаксис.
Пока это бета версия, мусор будет.
Возможно, но это бета тестирование. Пока что уделять этому время не буду. Когда программа покажет результат, примусь за внешний вид))) и все красивости.
Вопрос, какие шаблоны добавить в программу?
Вроде-бы нечего не забыл)
Спасибо за внимание 🙂
Сообщение отредактировал vadeus — 13.04.14, 08:04
Новая версия, от 13-04-2014 Скачать
версия: 1.0 BETA Android_Script_BETA.zip ( 7.62 МБ )
Добавлено:
1. Добавлен «Статус сборки» ( теперь будет видно что пошло не так)
2. Исправлены некоторые ошибки
3. В блок «О программе» добавлены ссылки на обсуждения.
4. Добавлен бинарник «ROM CyanogenMod 10.1 Android 4.2.2 (09-07-2013)» т.к. он хорошо работает с старыми рекавери CyanogenMod
Источник
All in one script android
Apps2SD: All in One Tool
версия: 16
Последнее обновление программы в шапке: 13.09.2018
Для функционирования программы необходимы права root пользователя.
Краткое описание:
Перенос, ссылка приложений на SD, инструмент все в одном.
Apps2SD это приложение которое может не только переносить данные приложений на sd-карту, но и ‘все в одном’, что включает в себя множество интересных функций. Оно единственное в своем роде.
Для работы Apps2SD важно знать о необходимости того, что:
• на устройстве должны быть получены root-права и они должны быть выданы Apps2SD
• необходимо иметь 2 раздела на sd-карте (в приложении предусмотрена возможность создания двух разделов)
• должен быть установлен Busybox (в случае отсутствия будет предложено скачать)
• должен быть установлен Chainfire SuperSu при пользовании Android 5 (Lollipop) или выше, если вы хотите использовать возможность монтирования папок (Folder Mount), а также ссылать obb и external data на sd-карту. Но Apps2SD также отлично работает и с другими приложениями по управлению root-правами.
Возможности Apps2SD:
• Ссылание apk, odex, dex, lib, internal data, external data и obb папки пользовательских/системных приложений на sd-карту.
• эмулятор терминала (Terminal Emulator)
• монтирование и ссылание папок (Mount folder, Link folder)
• очистка следов сломанных приложений (удаление неиспользуемых файлов и устранение ошибки загрузки/установки в Google Play)
• скрытие приложений и игр (возможно создание доступа с паролем)
• создание/восстановление бэкапа приложения/игры/sd-карты
• дополнительные опции перезагрузки
• запись с экрана (для пользователей Android Kitkat или выше)
• менеджер задач (Task Manager) (очищение ОЗУ с помощью остановки запущенных процессов)
• менеджер приложений (App Manager) (включение/отключение служб/активити/приемников/контент-провайдеров)
• менеджер подкачки: ускоритель ОЗУ (создание/управление разделами/файлами подкачки)
• ускоритель sd-карты (увеличить скорость работы внутренней/внешней sd-карты)
• тест скорости sd-карты (тест скорости чтения/записи вашей sd-карты)
• инструмент для работы с разделами (возможность создания до 3-х разделов на вашей sd-карте)
• гибернация приложений (гибернация пользовательских/системных приложений при выключении экрана)
• менеджер скриптов (создание/запуск кастомных linux скриптов. Создание ярлыков на домашнем экране, для быстрого доступа к скриптам)
• переключатель частот ЦП (переключите частоту ЦП для продления срока службы аккумулятора (уровня заряда), когда экран выключен)
• журнал логов (просмотр/сохранение/отправка логов вашего устройства)
• фикс sd-карты (фикс прав-записи на внешнюю sd-карту)
• удаление системных приложений (в том числе программного обеспечения, содержащего вирусы)
• перенос приложений на sd-карту используя стандартный app2sd метод (принудительное перемещение в случае, если перенос не поддерживается приложением)
• включение и отключение приложений
• ссылание, возврат ссылания, включение, отключение, конвертирование, интегрирование, очистка data/cache, перенос на sd-карту, перенос на устройство и много других функций
• автоматическое ссылание только что установленных приложений (опционально)
• поддержка 32/64-битных устройств
Как это работает:
Ссылание приложений и игр (Link2SD)
Apps2SD перемещает apk, odex, dalvik-cache, lib и файлы internal data во второй раздел на вашей карте, который ОС монтирует при загрузке и создает ссылку-идентификатор в исходном местоположении. Это позволяет перенести большую часть данных (при этом сохраняется вся структура файлов и папок), в то время как система продолжает думать что данные все еще в памяти устройства.
Ссылание obb и external data (Obb2SD):
На устройствах, которые имеют эмулируемую (внутреннюю) sd-карту, файлы obb и external data на самом деле располагаются во внутреннем хранилище, не на внешней (реальной) sd-карте. Этот метод позволяет переместить эти файлы в первый/второй раздел вашей внешней sd-карты с опциональной привязкой команды для монтирования/перемонтирования иерархии файлов.
Аналог программы: Link2SD
Источник
Kotlin DSL: Gradle scripts in Android made easy
If you are scared of Gradle scripts with unfamiliar groovy syntax files, then Kotlin DSL is made for you. Its time to face the Gradle scripts with more confidence. In this article, we will convert some common Groovy-based Gradle scripts into Kotlin DSL scripts.
Let’s get started
Open half baked side android project 😉 of yours. In your project-level root folder create a folder named buildSrc same as that of your app/ folder in your project. This is a special folder to enable the Gradle scripts at the project level. Hit the sync button and you will see how these changes and adds some temporary files inside it.
Half the battle is done 😀 now in order to enable the Kotlin DSL we gotta do something more here. So put our lazy brain to work and create a file inside buildSrc naming it build.gradle.kts open now the newly created file to add some code that tells Gradle to enable the Kotlin-DSL plugin for our project.
Sync now, That’s it Battle is won, and Kotlin DSL is enabled in our project.
Is there anything left to do? 🤔
Yes, whatever we have done is of no use until we put Kotlin DSL into some action.
Kotlin DSL brings the simplicity of the Kotlin language syntax and rich API set right into the script files on top of that code completion makes it perfect to work with Gradle script files. We will use this to manage our dependencies and project settings configurations more elegantly. Kotlin DSL files have extension as .kts so we will be converting all of our .gradle files to .gradle.kts
Before converting our files to Kotlin DSL let’s have some necessary files in place in order to go ahead. Create folders inside the buildSrc folder as below and create the stated files.
AppConfig.kt:
This file helps us manage our app-level configurations related to the project at once place.
Versions.kt
This file helps us separate our versioning of the libraries in one place.
AppDependencies.kt
This file holds all the dependencies of our app related to UI, test, and other third-party libraries. Apart from that this also holds the Kotlin extension functions for implementation, testImplementation, androidTestImplementation, kapt which basically now accepts a list of String (dependencies) which is helpful for adding multiple dependencies at once instead of adding one by one in build.gradle file. You can play around and separate dependencies based on the module name also by creating a different list of dependencies for your module and add all at once by using a single line of code Gradle script.
Here is how it will look like when we are done adding all the Kotlin files.
Also, it’s no hard and fast rule we can also manage all these constants in one file also but if your project is large enough to make you go mad for a single change then it’s better to have separate the concerns in different files for different purposes. Let’s convert
settings.gradle
Our existing code for settings.gradle file as below
settings.gradle.kts
include is now just a function taking vararg of String to include the modules in the project. Moving next we gonna change our project level build.gradle file
build.gradle
build.gradle.kts
Kotlin DSL version is almost the same since it’s using DSL to map those syntaxes and tries to be as close as possible for example.
classpath is just a regular Kotlin function taking String as input. Which we all know and understand and can relate the syntax. Let’s see how our main app-level build.gradle file changes to build.gradle.kts
Plugins are the first thing in the main app-level Gradle file which enables the android support in regular Intellij project or Kotlin support in an android project or any third party plugin which needed at module level can be applied in this file, we will see show that changes
will be changed to
or you can use another way of adding plugins as shown below, the above one is the DSL way of doing things.
now let’s try to go chunk by chunk for an android block with the basic setup.
will be changed to
Now it’s possible to directly access the Kotlin object constants or any other constants like as shown above. Here we are using the earlier created constants in file AppConfig for the app level configurations. Next, let’s see how we can create the debug and release versions.
will be changed to
you don’t have to create debug because it’s there by default until unless needed to change some properties. If so then do something like this.
coming to the main dependencies this is how it was like before
will be now changed to below
this is quite maintainable, easy to read & understand.
putting all this together will look like as below.
If you have any android module, conversion goes almost the same for the modules as well instead of using an android id plugin use library plugin id.
Kotlin DSL is not limited to the usages across Gradle scripts it’s way broader than just scripting. Let’s go and explore this side of Kotlin DSL by putting this into implementation.
Styling TextView using Kotlin DSL.
Let’s start by creating the backbone which will support the DSL.
in our MainActivity we will use this as follow.
Output:
This is the very basic example of Kotlin DSL, we can write to express almost anything using this. This is a much more clean and expressive way of doing programming. Since it uses Kotlin lambda expressions extensively to achieve this, we should be conscious of the extra classes it generates at the byte code level. So how to fix this 🤔, simply try to inline the lambda expressions where ever possible in order to reduce the extra class which would get generated for the small code blocks.
That’s it folks for today. Please be generous enough to comment for feedback or suggestions or any queries. Thanks for reading 😊.
Источник