android - 使用 Intents 播放音频文件

标签 android android-intent

我正在尝试创建一个只播放 .mp3 文件的媒体播放器。我已创建列表并显示在我的应用程序上,但我无法让它播放歌曲。有人建议我使用 Intent ,但我不知道该怎么做。

这是代码;

ListView list;
Cursor cursor;
int columnIndex;
int count;
private ArrayAdapter arrayAdapter;
private Button dropbox;

public MainActivity()
{

}

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dropbox = (Button) findViewById(R.id.dropbox);
    list = (ListView) findViewById(android.R.id.list);

    dropbox.setOnClickListener(new View.OnClickListener() 
    {

        @Override
        public void onClick(View v) 
        {
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.dropbox.com"));
            startActivity(i);
        }
    });

    String[] displayMusic = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};

    cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, displayMusic, null, null, null);

    //0 is the id for a mp3 file on the sd card
    //1 is the file name of the mp3 file on the sd card
    final ArrayList<String> listOfMp3s = new ArrayList<String>();
    final ArrayList<String> listOfIds = new ArrayList<String>();
    while (cursor.moveToNext())
    {
        if(cursor.getString(1).endsWith("mp3"))
        {
            listOfMp3s.add(cursor.getString(1));
            listOfIds.add(cursor.getString(0));
        }
    }



    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listOfMp3s);
    list.setAdapter(arrayAdapter);
    list.setOnItemClickListener(new OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
        {
            Intent songPageIntent = new Intent(getApplicationContext(), SongPage.class);
                            startActivity(songPageIntent);
        }
    });
 }

最佳答案

这样试试

String name = "http://dl.dropboxusercontent.com/sh/t0in0j8jgsr9wft/abc.mp2";
Uri a = Uri.parse(name);

Intent viewMediaIntent = new Intent();   
viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);   
viewMediaIntent.setDataAndType(a, "audio/*");           
viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(viewMediaIntent);

关于android - 使用 Intents 播放音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16018130/

相关文章:

android - 即使在 "killed"之后,应用程序仍会继续运行

android - 从另一个项目调用 Activity

android - 将 intent extras 从谷歌云消息接收器传递到 Activity 是空的

java - Intent.putExtras 大小限制?

Android/iOS 指纹扫描仪用作身份验证

Java Android : How to force only one instance of an app (singleTop not working correctly)?

android - 与模拟器和 Web 相比,真实 Android 设备中的 Retrofit 响应时间更慢

java - 创建具有样式但没有属性的 TextView(在代码中)

android - <include> 标签覆盖属性

android - 使用 SAF 访问 Google Drive 时如何刷新内容