How to list all default music players and open one - java

I want to click my music icon and let the user decide which music player they want to use, if google play music or another one they have installed
so far I have done this but it just launches the default google play music app
try {
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MUSIC);
startActivity(intent);
} catch (Exception e) {
Log.d(TAG, "Exception for launching music player "+e);
}
Instead I was searching in all SO for this and cant find how to list all music players , select one and open it, any ideas ?
This is what I want to do

You can set data type for your Intent:
public void openMusicPlayerChooser(File musicFile) {
if (Build.VERSION.SDK_INT >= 24) {
try {
Method method = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
method.invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
}
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(musicFile), "audio/*");
startActivity(intent);
}

This works for me
Intent intent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MUSIC);
startActivity(intent);

Related

Android Location capture in every 15 minutes

I am developing an android app using Java with minimum api level is 16 and target level is 29. Application worked perfectly with android emulator(android 10). But when i checked the same with my vivo phone, foreground service is killed by os. After research i noted that auto start option is disable in phone. I got a code to redirect the user to enable auto start option. But it will call every time when the use call the activity. I have mentioned the same code. Kindly help me regarding the following questions
How to check auto start is enabled in phone pragmatically?
Is there any other option available to overcome the app killing issue?
enter code here
private void addAutoStartup() {
try {
Intent intent = new Intent();
String manufacturer = android.os.Build.MANUFACTURER;
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if ("Letv".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
} else if ("Honor".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
}
else if ("Huaewi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
}
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
startActivity(intent);
}
} catch (Exception e) {
Log.e("exc" , String.valueOf(e));
}
}

How to stream music from url with Java - Android

I'm totally new to Android Development and to Android devices in general, so I don't know how things are working here.
I want to make an app that will stream music from my url and still playing the song after I minimize the application.
I searched my question but a lot of answers were for mp3 songs or other types, but my url is from a live radio so it isn't one song only.
One of the answers that I found and were good for my problem was this and uses this code:
Uri myUri = Uri.parse("your url here");
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(myUri, "audio/*");
startActivity(intent);
This prompt me to choose a music player.
Is there any way to just press my "play" button and hear the music?
In my iOS app I use this code and I can start and stop the streaming music whenever I want without an external player:
func prepareToPlay() {
let url = URL(string: "myUrl")
playerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)
player?.play()
}
Thanks in advance
EDIT
After suggested in comments and answer I tried to play it with MPlayer, I made a function and I called it when I tapped my button like this:
public void playM() {
String url = "http://android.programmerguru.com/wp-content/uploads/2013/04/hosannatelugu.mp3";
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mPlayer.start();
}
But I get an error (the fourth message) and I saw in the logs this:
Unable to create media player
prepareAsync called in state 1, mPlayer(0x0)
start called in state 1, mPlayer(0x0)
error (-38, 0)
Intent with ACTION flag is intended to open another app in most cases. Since you don't need it. You want your own custom player. So Android has a Media Player class for such scenarios.
Create instance of it and pass your stream-URL. Now, set the data-source and call prepare() after that in onBtnClickListener() start the music by calling mp.start()
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
P.S: Catch all the exceptions and make sure the PERMISSIONS in manifest file
Intent is using only for sending some data between activities/services and system. It won't play the music. It don't do anything except saying to some activity what to do. You need the mechanism which will play your multimedia stream. You should use MediaPlayer class for playing multimedia inside your application.
Here's some tutorial, how to play music from stream: http://programmerguru.com/android-tutorial/android-mediaplayer-example-play-from-internet/

How to Add MX Player as the default player in an android application?

I want a way to set up a MX Player to play videos in my application.
This will launch any installed version of MX Player(Not tested).You need to add data to the intent to play videos. Good luck with your app.
Intent intent;
PackageManager packageManager=getPackageManager();
try {
intent= packageManager.getLaunchIntentForPackage("com.mxtech.videoplayer.pro");
if (null != intent)this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
//MX Player pro isn't installed
try{
intent= packageManager.getLaunchIntentForPackage("com.mxtech.videoplayer.ad");
if (null != intent)this.startActivity(intent);
}
catch (ActivityNotFoundException e) {
//No version of MX Player is installed.You should let the user know
}
}

shortcut not opening app on android homescreen

I have installed a few apps on my android device, and I developed a code to create a shortcut for them, they all work apart from one app, but if I manually drag the app on homescreen it works, I'm really confused... the next code is what I used to create the shortcuts
try
{
//Log.i("shortcut method in androidhelper start","in the shortcutapp on create method ");
boolean flag =false ;
int app_id=-1;
PackageManager p = getPackageManager();
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> res =p.queryIntentActivities( i,0);
//System.out.println("the res size is: "+res.size());
for(int k=0;k<res.size();k++)
{
//Log.i("","the application name is: "+res.get(k).activityInfo.loadLabel(p));
if(res.get(k).activityInfo.loadLabel(p).toString().equals("Kortext")){
flag = true;
app_id = k;
break;
}
}
if(flag)
{
ActivityInfo ai = res.get(app_id).activityInfo;
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(ai.packageName, ai.name);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.addCategory(Intent.ACTION_PICK_ACTIVITY);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
// Sets the custom shortcut's title
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Kortext");
BitmapDrawable bd=(BitmapDrawable)(res.get(app_id).activityInfo.loadIcon(p).getCurrent());
Bitmap newbit;
newbit=bd.getBitmap();
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, newbit);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(intent);
}
else
{
// throw new UserException(UserException.KErrGeneral,"Application not found");
}
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
//throw new UserException(UserException.KErrGsmRRNoActivityOnRadioPath,e.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
//throw new UserException(UserException.KErrGeneral,e.getMessage());
}
Any ideas?
I figured it out, I also had to change the intents to new Intent(Intent.ACTION_MAIN);

how can I use GET_CONTENT for audio only?

After using this code:
public void getContent() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(intent, REQUEST_CODE_GET_CONTENT);
} catch (ActivityNotFoundException e) {
// No compatible file manager was found.
Toast.makeText(this, R.string.no_filemanager_installed,
Toast.LENGTH_SHORT).show();
}
}
the phone pops up a window where you can choose between audio or images file. I just want the audio and I don't want that the user can choose the image files. how can I do to not show this window and automatically go to audio selection?
Try intent.setType("audio/*");

Categories