Tuesday, June 5, 2012

Start Intent to choice "audio/mp3" using installed app

By starting Intent with action of "Intent.ACTION_GET_CONTENT" and type of "audio/mp3", we can open installed app on Android devices to choice mp3 file.

Choice mp3 file with installed app


package com.exercise.AndroidPlayer;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AndroidPlayerActivity extends Activity {
 
 TextView info;
 Button buttonOpen;
 
 final static int RQS_OPEN_AUDIO_MP3 = 1;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonOpen = (Button)findViewById(R.id.open);
        buttonOpen.setOnClickListener(buttonOpenOnClickListener);
        
        info = (TextView)findViewById(R.id.info);
    }
    
    OnClickListener buttonOpenOnClickListener
    = new OnClickListener(){

  @Override
  public void onClick(View arg0) {
   Intent intent = new Intent();
   intent.setType("audio/mp3");
   intent.setAction(Intent.ACTION_GET_CONTENT);
   startActivityForResult(Intent.createChooser(
     intent, "Open Audio (mp3) file"), RQS_OPEN_AUDIO_MP3);
   
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == RESULT_OK) {
   if (requestCode == RQS_OPEN_AUDIO_MP3) {
    Uri audioFileUri = data.getData();
    
    info.setText(audioFileUri.getPath());
   } 
  } 
 }

}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <Button
        android:id="@+id/open"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Open MP3 file" />
    <TextView
        android:id="@+id/info"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


Next:
- Play "audio/mp3" with MediaPlayer


No comments: