Making mediaserver immediately scan a file created through ADB


Question

The mediaserver in my stock and rooted Android 6.0.1 (running in Nexus 6) doesn't detect new files created or moved to into /sdcard using adb. It doesn't detect until I do a soft/full reboot which I find unacceptable to perform.


I'm able to manually run mediaserver using command-line to begin file scanning again# and I want this to be done automatically and immediately whenever a new file is created under /sdcard. At the moment, I have Tasker run the mediaserver whenever USB cable is unplugged.*


The obvious choice here seems to be an automation app of which I tried Tasker and Automate, and both amazingly failed to detect new files, particularly under /sdcard/Music, when created through adb. However, if an app created files in any directory under /sdcard those two apps immediately detected the changes. I also tried pushing files to /storage/emulated/0/ instead of /sdcard/ and made corresponding changes in those two apps' triggers.That step didn't benefit me.


It is to be noted that I observed this problem in stock Android 5.1.1 and a CM13 snapshot build as well.


So, how do I achieve the goal?


Update


I'm aware of the possibility of creating an alias in the OS running in my PC which would execute a script providing a way to push the file as well as run the mediaserver. However, it is something I would like to avoid as much as possible.


* I was using it but later switched to a script executed from PC using an alias. However, I do not want to depend upon any of the two methods. My fingers are comfortable with typing adb push instead of adb_push or some other but single word.


Update 2



  • I do not intend to restrict myself to a particular directory, such as Download and neither pushing files into the latter actually works.

  • I would like to stress that I'm not asking for how to run mediaserver. That I already know. All I'm looking for is: Whenever I do adb push FILE /sdcard/FILE the mediaserver should automatically and immediately kick in and scans the file. Regardless of any perceivable performance issue, I want it to kick in every single time.


Update 3


Okay, I may be using an incorrect term. Perhaps mediaserver and media scanner are terms for two different things in Android. In the case of confusion, please stick with
"media scanner" for both the current revision and the bounty note.


Update 4


# Courtesy of androidyue for this helpful resource, any of the following command in preformatted text is what I can use in my device to make media scanner scan the file.



# FILE_PATH refers to the location of pushed file in Android. E.g. /sdcard/Music/lolcat.mp3

am broadcast -a android.intent.action.BOOT_COMPLETED -n com.android.providers.media/.MediaScannerReceiver
am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://FILE_PATH # guaranteed to work. See https://goo.gl/lH0CLT for proof.
am broadcast -a android.intent.action.MEDIA_MOUNTED -d file://FILE_PATH

Update 5


Per the suggestion from Manubhargav, I tried Sarkie's MTPFix available here. It didn't work, both in stock Android 6.0.1 and CM13. I saw the following entry when I enabled the service for that app.


04-07 09:38:14.771  3383  3383 I MTPService: Watching /storage/emulated/0

I later pushed a sound file into /storage/emulated/0/ and nothing showed up in my music player. Logcat also didn't display anything useful either.


By the way, this app uses FileObserver, so I'm not surprised if it couldn't detect files created using adb, since it is the same issue with the automation apps I tried.




Note: Please post an answer only when you've tested it yourself. Thank you!


Answer

Okay, it seems the answer is trivial. My fingers don't have to lose the comfort of typing adb push, yet I would be able to cause media scanner scan my pushed file, automatically and immediately. Here's my script tweaked to my needs:



(Note: root access is not required in Android)




#!/bin/bash

function push_file () {
target="${ @: -1 } ";
file_path="${ @: -2:1 } ";
[[ "$prog_bar" == "-p" ]] && adb "$@" || $call_adb push -p "$file_path" "$target";
}

function broadcast () {
file_name="$(basename "$file_path")";
[[ `echo "${ target: -1 } "` != "/" ]] && unset file_name;
[[ `echo "${ target:0:1 } "` != "/" ]] && target="/${ target } ";
$call_adb shell 'am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d '"\"file://$target$file_name\""'' > /dev/null;
}

if [[ "$1" == "-s" ]]; then
if [[ "$3" == "push" ]]; then
prog_bar="$4";
call_adb="adb -s $2";
push_file "$@" && broadcast;
else
adb "$@";
fi
elif [[ "$1" == "push" ]]; then
prog_bar="$2";
call_adb="adb";
push_file "$@" && broadcast;
else
adb "$@";
fi


I then setup an alias named adb in .bashrc like this:



alias adb='bash FILE'  # FILE refers the file path of the said script


This was possible thanks to the very helpful article: Handling positional parameters at Bash Hackers Wiki.



Note: the script more or less requires a *nix based OS in PC with version 4.x of Bash installed and support for .bashrc. If you intend to use the script, you're encouraged to edit it to suit your working style.


Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes