2

我是 android 应用程序开发的新手,但我对 JAVA 和一般编程有很好的了解。我正在尝试为 android 编写一个应用程序,它可以将音乐文件排入 android 中的默认音乐播放器(如 Google Play 音乐)。我的应用程序决定何时播放哪首歌,但我不想编写一个成熟的音乐播放器应用程序。我只想为现有的播放器应用程序提供新音乐。

我正在寻找类似“应用程序间”通信(可能使用 Intent?)之类的东西,通过它我可以将内容提供给音乐播放器并可能控制播放器本身。

我不确定android中是否存在这样的设施,所以也欢迎其他替代建议。另外,如果我没有正确解释问题,请告诉我。

4

1 回答 1

1

Intents are a very powerful feature of Android to which there isn't any direct analog in Java. What you want to use is a mechanism known as an implicit Intent. Normally, when you launch one activity from another, you create an Intent and specify which activity to start. With an implicit Intent, you provide an action (Intent.ACTION_VIEW) and data (a URI pointing to a music file). Using an implicit Intent, you have a piece of data handled without knowing in advance which Activity will do the handling.

When you pass your Intent to startActivity(), the OS will attempt to resolve the data in the best way possible, typically popping up a list of apps that can possibly handle your data. The user selects the appropriate app and that app handles the Intent, playing your music file. Any app that registers as a service capable of potentially handling your data will show up in the list. After passing the Intent, your activity will go into the background, and the app handling the intent will come to the foreground.

Once the user has selected an app to handle the Intent from your Activity, that app will always be used to handle that kind of Intent by your Activity until you delete your own app's data.

Take a look at the official doc to get yourself started and then ask a new question when you have a more specific problem you're trying to address.

Here's a code sample that demonstrates a very simple implicit Intent example, by which a URL is opened without knowing which browser will open it:

package com.marsatomic.intentimplicitdemo;

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

public class MainActivity extends Activity
{
    public final static Uri URI = Uri.parse("http://www.marsatomic.com");

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

        Button buttonConnect = (Button)findViewById(R.id.button_connect);
        buttonConnect.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent i = new Intent(Intent.ACTION_VIEW, URI);
                startActivity(i);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
于 2013-05-20T05:47:18.710 回答