gpt4 book ai didi

android - setAction() 对 intent (Broadcast) 做了什么

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:14 27 4
gpt4 key购买 nike

intent(Service)中setAction()是做什么的

我不太明白 setAction () 的作用,我主要是在“服务到 Activity 数据传递”示例中找到它。字符串可以自由设置吗?它到底有什么作用?

When a broadcast intent is created, it must include an ACTION STRING in addition to optional data and a category string. As with standard intents, data is added to a broadcast intent using key-value pairs in conjunction with the putExtra() method of the intent object. The optional category string may be assigned to a broadcast intent via a call to the addCategory() method.

The action string, which identifies the broadcast event, must be unique and typically uses the application’s Java package name syntax. For example, the following code fragment creates and sends a broadcast intent including a unique action string and data:

 Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
intent.putExtra("HighScore", 1000); sendBroadcast(intent);

我见过的另一种变体是:

 Intent broadcastIntent = new Intent();

broadcastIntent.setAction("com.truiton.broadcast.string");
broadcastIntent.putExtra("Data", "Broadcast Data");
sendBroadcast(broadcastIntent);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction("com.truiton.broadcast.integer");
broadcastIntent.putExtra("Data", 10);
sendBroadcast(broadcastIntent);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent .setAction("com.truiton.broadcast.arraylist");
broadcastIntent.putExtra("Data", mList);
sendBroadcast(broadcastIntent);

这看起来更像是识别传入的数据类型。

它是指识别事件、传入的数据类型操作 还是每个Intent 创建?可以放生吗?

最佳答案

使用 <action>标签内 <activity>Manifest.xml 文件中设置操作的标记与在 java 文件中使用 intent.setAction 以编程方式设置操作相同。

这些通常用于广播接收器。

下面是一个xml例子:

<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.example.SendBroadcast" >
</action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" >
</action>
</intent-filter>
</receiver>

但是当您希望 BroadCastReceiver 以编程方式注册和取消注册时,可以使用 setAction()。

Intent intent = new Intent();
intent.setAction("com.example.SendBroadcast");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(intent);

有关更多信息,请查看:http://www.techotopia.com/index.php/Android_Broadcast_Intents_and_Broadcast_Receivers

关于android - setAction() 对 intent (Broadcast) 做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38260372/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com