如何将意图连接到方法

How to connect an intent to a method

我不知道如何指定意图过滤器调用的函数或如何从该意图中获取参数(数据)。

例如,在我的 AndroidManifest.xml 文件中有以下内容:

<intent-filter>
     <action android:name="android.intent.action.VIEW"></action>
     <category android:name="android.intent.category.DEFAULT"></category>
     <category android:name="android.intent.category.BROWSABLE"></category>
     <data android:host="example.com" android:scheme="http"></data>
</intent-filter>

用户转到 http://example.com/some-end-point - 弹出一个应用程序选择器,用户选择我的应用程序(我们称之为 MyApp)。那么在 MyApp 中调用了什么以及如何获取参数,在本例中是调用的 /some-end-point

How do I specify what block of code this intent refers to ... Do I register it within the Java code or do I specify it in the XML?

Sorry for the basic question but I've been unable to find this after quite a bit of searching and going through the sample code.

Maybe I have a fundamentally wrong assumption of the programmatic model used here?

好吧,这并不明显。在下面的主要 onCreate 内部,有一个全局的 getIntent() 可以访问,它不是由任何传递决定的。

让我们通过显示更大的 ActivityMain.xml

来建立更多上下文
   <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.VIEW"></action>
            <category android:name="android.intent.category.DEFAULT"></category>
            <category android:name="android.intent.category.BROWSABLE"></category>
            <data android:host="example.com" android:scheme="http"></data>
        </intent-filter>
    </activity>

这里的 android:name 是主要的 link 到 MainActivity class 里面 MainActivity.java 这通常是默认样板的一部分(如在您开始新项目时为您创建的模板代码中)。

在此 class 中有一个方法 onCreatelife-cycle rules 之后被调用(简单来说;当您启动该应用程序时它会出现在屏幕上)。在 onCreate 中你可以这样调用:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("FILTERME", "intent - " 
              + getIntent().getAction() + " :: " 
              + getIntent().getDataString());
    }
    ...
}

现在给自己发电子邮件 link,例如http://example.com/some-end-point.

然后在您的 phone 上安装示例应用程序,并连接 USB 数据线和 adb 运行(我正在使用 android studio),查看电子邮件并单击 link,您应该会在日志中看到完整的 URI。

好吧:在一个包罗万象的函数中调用一个隐式全局状态的单例——一点也不明显(恕我直言,这是一个草率的设计)。鉴于此,可能有更好的方法来做到这一点。顺便说一句,我想通了 by looking at this code ...它回答了一些其他片段没有回答的问题。