Long press volume android

Как на Android переключать песни длительным нажатием на кнопки регулировки громкости

Если вы когда-нибудь ранее устанавливали кастомные прошивки (ROM) на свой смартфон, то, скорее всего, видели функцию, позволяющую назначить на длительное нажатие кнопки громкости управление воспроизведением мультимедиа. Если эта опция включена, вы можете зажать кнопку увеличения громкости, чтобы перейти к следующему треку, или таким же образом зажать кнопку уменьшения громкости, чтобы вернуться к предыдущей композиции. Возможность переключать песни нажатием на кнопки громкости настолько популярна среди пользовательских кастомных прошивок, что мы удивлены тому, что она до сих пор не попала в лаунчер какого-нибудь крупного производителя смартфонов.

Приложениям в Android нельзя задействовать длительное нажатие клавиш

По правде говоря, назначить управление воспроизведением музыки на кнопки регулировки громкости можно при помощи популярных приложений Tasker или Button Mapper, ведь они как раз и созданы для того, чтобы переназначать в Android функциональность различных физических клавиш. Однако ни одно из этих приложений не умеет повторить в точности то, что могут предложить кастомные прошивки. Если вы используете Tasker или Button Mapper, у вас есть возможность переназначить на кнопки увеличения и уменьшения громкости только одинарное или множественное нажатие. Приложения, подобные этим, обычно используют для перехвата нажатий клавиш громкости службу Специальные возможности, но ни одно из них не может перехватить длительное нажатие клавиш громкости, когда экран смартфона выключен.

Вскоре после выпуска исходного кода Android 8.0 Oreo разработчики с ресурса XDA Developers обнаружили в Android новую функцию, которая позволяет сторонним приложениям видеть, когда система реагирует на длительное нажатие клавиш регулировки громкости. Разработчики предположили, что этот новый API в будущем позволит приложениям контролировать длительное нажатие на кнопку регулировки громкости, даже когда экран смартфона выключен, что, в конечном итоге, позволит в сторонних приложениях воспроизвести популярную функцию из кастомных прошивок без необходимости рута.

Именно это и сделал пользователь с форума XDA, создав приложение Next Track. Это приложение с открытым исходным кодом, использующее вышеупомянутый API, позволяет переключать композиции длительным нажатием любой кнопки громкости даже при выключенном экране. Оно работает на любом устройстве под управлением Android 8.0 Oreo, Android 8.1 Oreo, Android 9 Pie или Android Q.

Чтобы настроить Next Track, все, что вам нужно сделать, это установить само приложение из Google Play и запустить следующую ADB-команду:

./adb shell pm grant com.flar2.volumeskip android.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER

С более подробной инструкцией для MacOS и для Windows от разработчика можно ознакомиться здесь.

Этот же разработчик работает над обновлением своего приложения Button Mapper, чтобы оно использовало новый API. Для реализации в Button Mapper переключения композиций длительным нажатием кнопок громкости разработчику пришлось использовать в каком-то роде хакерской метод, а поэтому вся функциональность сбрасывалась при каждой перезагрузке устройства, чего не должно происходить при использовании нового API.

Поскольку это скрытый API, нет гарантии, что Google не убьет доступ к нему в будущем обновлении Android. Начиная с Android Pie, Google работает над ограничением недокументированных/скрытых API, поэтому этот способ может перестать работать в финальной версии Android Q или Android R.

Приложение: Next Track
Разработчик: flar2
Категория: Музыка и аудио
Цена: Бесплатно
Скачать: Google Play

Делитесь своим мнением в комментариях под этим материалом и в нашем Telegram-чате.

Источник

This Android app lets you long press the volume buttons to skip songs while the screen is off – WITHOUT Root!

If you’ve ever installed a custom ROM before, then there’s a good chance you’ve seen a feature that lets you remap a long press of the volume button to control media playback. With this option enabled, you can long press the volume up button to skip to the next track or long press the volume down button to return to the previous track. The ability to skip songs with volume button presses is so ubiquitous among custom ROMs that we’re surprised to see it hasn’t made its way into software from major OEMs.

We’ve covered ways to control music playback via the volume buttons using apps like Tasker or Button Mapper, but none of these apps replicate exactly what custom ROMs are able to offer. If you use Tasker or Button Mapper, you can only remap single or multi-presses of the volume up and down buttons. Apps like these either listen for changes in the media volume or use an Accessibility Service to intercept button presses from the volume keys, but neither solution is viable to intercept long-pressing of the volume keys when the screen is off.

Shortly after the release of Android 8.0 Oreo’s source code, I spotted a new Android feature that would allow an Android app to be set as the “volume key long press listener.” We speculated that this new API would allow apps to control the long-press volume button behavior when the screen is off, thus finally making it possible to replicate the popular custom ROM feature without needing root. Although the feature was implemented in AOSP, Google never added a user-facing way to set an app as a volume key long press listener. Like with Android’s hidden navigation bar customizer, this feature can still be used even without an implementation in the Settings app.

Читайте также:  Визуальный редактор для android

That’s exactly what XDA Member Cilenco did with the Skip Track by Volume Keys app. It’s an open source app that uses the hidden volume key long press listener API to let you change music tracks with a long press of either volume button even while the screen is off. It works on any Android 8.0 Oreo, Android 8.1 Oreo, Android 9 Pie, or Android Q device. The app was developed a few months after we published our article (the developer even cites the article as their inspiration for the app), but it was never shared on our forums until late last month when it was finally brought to our attention. We quickly took it for a spin to see if it worked—and it does! Here’s a hands-on video from XDA TV’s Max Weinbach:

To set it up, all you have to do is install the APK from GitHub and run the following ADB command:

Then, enable the app’s Notification Listener service. This Notification Listener service doesn’t actually do anything, it’s just there to make sure the app doesn’t get killed in the background. On my Huawei Mate 20 X, I had to disable EMUI 9’s aggressive memory optimization feature, but after that I can confirm that it does work on EMUI. Since this is a hidden API, there’s no guarantee that Google won’t kill access to it in a future Android release. Since Android Pie, Google has been working on restricting undocumented/hidden APIs, so this may not work in the final release of Android Q or Android R.

Alternatively, if you would rather not install the APK from GitHub, you can try the newly updated release of Next Track (version 1.18) from XDA Recognized Developer flar2. He worked quickly to update this app after I informed him of this API, so go check that out if you want something a bit more customizable. Instructions on how to set it up can be found here. The developer is working on updating his Button Mapper app to use the new API, too. Button Mapper’s existing method to remap long presses of the volume button while the screen is off was a bit hackier and would reset on every reboot, but the new API persist across boots.

Источник

Android Oreo System Apps Can Set Volume Key Long-Press Listeners

Adding additional functionality to various hardware and software buttons on our devices is something Android enthusiasts have been doing for a while. Most people know about applications such as Button Mapper from XDA Recognized Developer flar2, and we even spoke about other remapper solutions back when the Galaxy S8 was released. While those solutions handled these actions in a certain way, Google looks to be implementing a listener in Android Oreo for long-pressing the volume keys. This means that potentially, applications in the future might be able to react to volume key long presses even while the screen is off, which could be used to bring an often-requested feature over from custom ROMs – music track control with volume key presses.

We do want to mention that this feature isn’t actually enabled in the user-facing build that we have available to us right now. Support for it is there though, as evidenced by the commit we found, and that means it can be enabled by the OEM for your specific device. As mentioned, traditional remapping applications work by detecting if a KeyEvent has been sent (with long presses, these apps measure the time between a key down and key up event whereas with double presses they measure the time between down presses), but these KeyEvents are only sent while the screen is on. Furthermore, they also typically require the use of an Accessibility Service which can be taxing on the performance.

Your typical button remap solution can be considered to be a workaround to be used to toggle the torch on or off, opening an application, pulling down the notification panel and so on. However, what Google has implemented into Android Oreo takes this a step further with letting system applications themselves set up these volume button long-press listeners. This could allow the user to trigger something within the application itself once the platform detects a volume button has been held down for a few seconds.

The way Google has included support for this in Android Oreo, this will only work for “privileged” (aka pre-installed system) applications out of the box. The OEM just needs to allow the privileged application to have the android.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER permission in order to set the listener. However, we’ve been able to grant permissions like these with ADB commands so it’s possible that those of us in the know could manually set this for a 3rd-party applications too.

XDA » Mini XDA » Android Oreo System Apps Can Set Volume Key Long-Press Listeners

Источник

[MOD][HOW-TO][2.0] Long press volume to skip tracks (the right way!)

loserskater

Inactive Recognized Developer

Now includes checkbox in settings to enable and disable!

Читайте также:  Карты для андроида гонки

Thanks to jakubklos for his diff file and getting me in the right direction.
And a HUGE thanks to the CM team.

CODE IN RED IS NEW!
CODE IN BLUE IS MODIFIED!

Some of your lines/variables may be different.
I’ve attached the original and modified files so you can diff them yourself!

First, decompile SecSettings.apk. If you’re unsure how to do that you’re going to have some pretty big issues ahead.

Navigate to res/values/strings.xml
and add the following to the end:

Now let’s get into some smail.

Open up com/android/settings/SoundSettings.smali

Now recompile SecSettings and the setting should be there. It won’t do anything though.

Next we need to decompile android.policy.jar.

First file is com\android\internal\policy\impl\PhoneWindowManager$PolicyHandler.smali

ISSUES:
Pressing volume up or down both turn the volume down(or up):

Attachments

Lilsir64

Member

Sent from my SAMSUNG-SGH-I747 using xda app-developers app

enewman17

Senior Member

This is great! made the changes and everything is running great.

Sent you a donation, Cheers! have a beer on me *Happy New Year!*

Thanks for all your hard work it is much appreciated

loserskater

Inactive Recognized Developer

This is great! made the changes and everything is running great.

Sent you a donation, Cheers! have a beer on me *Happy New Year!*

Thanks for all your hard work it is much appreciated

enewman17

Senior Member

I did not use the cond’s in green, I manually made the changes excluding them.
I am curious now if it will work using those cond’s I will try it later. I’m just so happy you were able to get it working! and well!

I had problems compiling it with apktool after I made the changes, but doing it manually worked and now apktool will compile and decompile without error. I don’t get it.

I’ve only tested it with the stock player and google play music and it works perfectly. I don’t use anything else so i didn’t test.

loserskater

Inactive Recognized Developer

I did not use the cond’s in green, I manually made the changes excluding them.
I am curious now if it will work using those cond’s I will try it later. I’m just so happy you were able to get it working! and well!

I had problems compiling it with apktool after I made the changes, but doing it manually worked and now apktool will compile and decompile without error. I don’t get it.

I’ve only tested it with the stock player and google play music and it works perfectly. I don’t use anything else so i didn’t test.

enewman17

Senior Member

I don’t remember, something like false value blah blah.

I diff’ed the the files using win merge and they are exactly the same. It’s not the first time it’s happened to me seem’s like it’s the way notepad++ saves the file. maybe. I had more problems using getdiz as a text editor. I don’t know maybe it’s me. But I do know it works.

When I changed the sound file in the SecContacts to get rid of the water drop sound from the dial pad I could not get apktool to compile it for the life of me, If I put the original sound back, apktool worked. Used manual commands and poof it worked like some sort of fairy magic. It was really starting to annoy me, but persistence pays off. Now apktool will decompile and compile my modded SecContacts with no problem. Also had the same problem when editing the SecPhone to get rid of the increasing ringtone. Same false value error. did it manually and it worked but I kind of figured it would happen cause that mod is kind of hacky to begin with, I didn’t delete the lines for that mod, but rather omitted those lines with a #

MikHaiL_08

Senior Member

upndwn4par

Inactive Recognized Developer

hellsgod

Senior Member

First of all, thank you for this Tutorial. I’ll try it now since a few hours, but it won’t recompile. I’ll tried it with the green ones and without it. Apktool gives me this errors:

I: Checking whether sources has changed.
I: Smaling.
Exception in thread «main» brut.androlib.AndrolibException: Could not smali file
: [email protected]
at brut.androlib.src.DexFileBuilder.addSmaliFile(DexFileBuilder.java:45)

at brut.androlib.src.SmaliBuilder.buildFile(SmaliBuilder.java:64)
at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:48)
at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:35)
at brut.androlib.Androlib.buildSourcesSmali(Androlib.java:243)
at brut.androlib.Androlib.buildSources(Androlib.java:200)
at brut.androlib.Androlib.build(Androlib.java:191)
at brut.androlib.Androlib.build(Androlib.java:174)
at brut.apktool.Main.cmdBuild(Main.java:188)
at brut.apktool.Main.main(Main.java:70)
Drücken Sie eine beliebige Taste . . .

Maybe someone have an idea. Thank you (=

enewman17

Senior Member

First of all, thank you for this Tutorial. I’ll try it now since a few hours, but it won’t recompile. I’ll tried it with the green ones and without it. Apktool gives me this errors:

I: Checking whether sources has changed.
I: Smaling.
Exception in thread «main» brut.androlib.AndrolibException: Could not smali file
: [email protected]
at brut.androlib.src.DexFileBuilder.addSmaliFile(DexFileBuilder.java:45)

at brut.androlib.src.SmaliBuilder.buildFile(SmaliBuilder.java:64)
at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:48)
at brut.androlib.src.SmaliBuilder.build(SmaliBuilder.java:35)
at brut.androlib.Androlib.buildSourcesSmali(Androlib.java:243)
at brut.androlib.Androlib.buildSources(Androlib.java:200)
at brut.androlib.Androlib.build(Androlib.java:191)
at brut.androlib.Androlib.build(Androlib.java:174)
at brut.apktool.Main.cmdBuild(Main.java:188)
at brut.apktool.Main.main(Main.java:70)
Drücken Sie eine beliebige Taste . . .

Maybe someone have an idea. Thank you (=

svfreddy

Senior Member

wali01x

Senior Member

loserskater

Inactive Recognized Developer

svfreddy

Senior Member

Sent from my SPH-L710 using xda app-developers app

Unknownforce

Retired Recognized Developer

Thanks, I fixed ours using this in the Sprint section (here).

But just an FYI, I used WinMerge to check diff’s between your org and mod, and it looks like you changed a bunch of :cond’s towards the end which was unnecessary.

Читайте также:  Yandex mail для андроид

Here is the last part that is needed to change:

And here is where some of the unnecessary changes are:

For some reason you increased all the :cond’s by 2, which doesn’t actually change anything, as this is just a «label» for the if statements to goto if the statement returns true.

Just thought I’d point that out.

But other than that, nice job! No more need for those extra files. Simple code modification.

I’m curious though, for my own sanity anyways, what’s the main difference here between the this mod and the original mod. (which didn’t work, properly, in JB) I know the original one sent the MEDIA_NEXT and MEDIA_PREVIOUS keys to the system, and this was getting interpreted incorrectly and being sent to the default Media Player, regardless of what currently had Audio Focus.

What does this one use as it’s method of changing the tracks, something more direct, or does it tap into another type of Media key?

I could go through the code and figure it out, but I’m too lazy right now.

WhiteiceDMSTech

Senior Member

Thanks, I fixed ours using this in the Sprint section (here).

But just an FYI, I used WinMerge to check diff’s between your org and mod, and it looks like you changed a bunch of :cond’s towards the end which was unnecessary.

Here is the last part that is needed to change:

And here is where some of the unnecessary changes are:

For some reason you increased all the :cond’s by 2, which doesn’t actually change anything, as this is just a «label» for the if statements to goto if the statement returns true.

Just thought I’d point that out.

But other than that, nice job! No more need for those extra files. Simple code modification.

I’m curious though, for my own sanity anyways, what’s the main difference here between the this mod and the original mod. (which didn’t work, properly, in JB) I know the original one sent the MEDIA_NEXT and MEDIA_PREVIOUS keys to the system, and this was getting interpreted incorrectly and being sent to the default Media Player, regardless of what currently had Audio Focus.

What does this one use as it’s method of changing the tracks, something more direct, or does it tap into another type of Media key?

I could go through the code and figure it out, but I’m too lazy right now.

Here from the Sprint GS III forums as unknownforce was able to convert your work to function for us Sprint folks. Just wanted to say thank you loserskater for your hard work on this and for getting this working. I have been waiting for this forever since upgrading to 4.1

Thanks loserskater and also thanks unknownforce,
Whiteice

loserskater

Inactive Recognized Developer

Thanks, I fixed ours using this in the Sprint section (here).

But just an FYI, I used WinMerge to check diff’s between your org and mod, and it looks like you changed a bunch of :cond’s towards the end which was unnecessary.

Here is the last part that is needed to change:

And here is where some of the unnecessary changes are:

For some reason you increased all the :cond’s by 2, which doesn’t actually change anything, as this is just a «label» for the if statements to goto if the statement returns true.

Just thought I’d point that out.

But other than that, nice job! No more need for those extra files. Simple code modification.

I’m curious though, for my own sanity anyways, what’s the main difference here between the this mod and the original mod. (which didn’t work, properly, in JB) I know the original one sent the MEDIA_NEXT and MEDIA_PREVIOUS keys to the system, and this was getting interpreted incorrectly and being sent to the default Media Player, regardless of what currently had Audio Focus.

What does this one use as it’s method of changing the tracks, something more direct, or does it tap into another type of Media key?

I could go through the code and figure it out, but I’m too lazy right now.

That’s why I added the conds in green so you don’t have to change all of the ones after. But if you add the 21 and 22 you’ll have multiple instances which throws errors when trying to compile.

The difference between this and the previous mod is that sending the media button presses would send an ordered broadcast and the app with the highest priority would take the broadcast and see if it needed it and then pass it along if it didn’t. Well must audio apps haven’t been updated to use this method. And if you changed it to just broadcast instead of offered all media players would get the broadcast do you’d have a bunch of apps trying to all play music. This uses private apis that that only the system can use and it’s the same method the lockscreen controls use which is controlled by the audio service instead of broadcasts. I hope that all makes sense

Источник

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