android+后台服务创建,Android中使用IntentService创建后台服务实例

intentservice提供了在单个后台线程运行操作的简单结构。这允许它操作耗时操作,而不影响ui响应。同样,intentservice也不影响ui生命周期事件,所以,它在某些可能关闭asynctask的情况下,仍会继续运行(实测在activity的ondestory里写asynctask无法运行)。

intentservice有如下限制:

1.它不能直接影响ui。要把结果反映给ui,需要发给activity

2.工作请求会顺序运行。如果一个操作未结束,后面发送的操作必须等它结束(单线程)

3.intentservice里运行的操作无法被中断

然而,在大多数情况下,intentservice是简单后台任务的首选方式。

本节展示了如何创建intentservice的子类,如何创建onhandleintent()回调,如何在androidmanifest.xml声明intentservice。

创建intentservice

定义一个intentservice的子类,覆盖onhandleintent()方法:

public class rsspullservice extends intentservice {

@override

protected void onhandleintent(intent workintent) {

// gets data from the incoming intent

string datastring = workintent.getdatastring();

...

// do work here, based on the contents of datastring

...

}

}

提示:其他service正常的回调,像 onstartcommand()在intentservice里会自动调用。在intentservice里,应该避免覆盖这些回调。

在androidmanifest.xml里定义intentservice

intentservice也是service),需要在androidmanifest.xml里注册。

android:icon="@drawable/icon"

android:label="@string/app_name">

...

android:name=".rsspullservice"

android:exported="false"/>

...

android:name属性指定了intentservice的类名。

注意:&ltservice&gt节点不能包含intent filter。发送工作请求的activity使用明确的intent,会指定哪个intentservice。这也意味着,只有同一个app里的组件,或者另一个有相同user id的应用才能访问intentservice。

现在你有了基础的intentservice类,可以用intent对象发送工作请求。

创建发送工作请求传给intentservice

创建一个明确的intent,添加需要的数据,调用startservice()发送给intentservice

/*

* creates a new intent to start the rsspullservice

* intentservice. passes a uri in the

* intent's "data" field.

*/

mserviceintent = new intent(getactivity(), rsspullservice.class);

mserviceintent.setdata(uri.parse(dataurl));

//call startservice()

// starts the intentservice

getactivity().startservice(mserviceintent);

提示:可以在activity or fragment的任意位置发送工作请求。如果你需要先取到用户输入,你可以在点击事件或类似手势的回调方法里发送工作请求。

一旦调用了startservice(),intentservice会在onhandleintent()工作,完了结束自身。

下一步是报告结果给原来的activity或fragment,下节讲如何用broadcastreceiver实现。请参考此文:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好,如果您想在 IntentService 使用 MQTT 协议进行消息传输,可以使用 Eclipse Paho Android 客户端库。以下是在 IntentService 使用 Paho Android 客户端库实现 MQTT 的基本步骤: 1. 添加 Paho Android 客户端库到您的项目。 2. 在 IntentService 的 `onCreate()` 方法创建 MQTT 客户端并连接到 MQTT 代理服务器。您需要指定代理服务器的地址和端口号。可以使用 `MqttConnectOptions` 类设置连接选项,例如设置连接的用户名和密码、清除会话标志等。 3. 在 `onHandleIntent()` 方法订阅主题、发布消息和处理接收到的消息。您需要实现 `MqttCallback` 接口,并在回调方法处理接收到的消息。 以下是在 IntentService 连接到 MQTT 代理服务器的示例代码: ```java public class MyIntentService extends IntentService { private static final String TAG = MyIntentService.class.getSimpleName(); private MqttAndroidClient client; public MyIntentService() { super(TAG); } @Override public void onCreate() { super.onCreate(); String brokerUrl = "tcp://mqtt.eclipse.org:1883"; String clientId = MqttClient.generateClientId(); client = new MqttAndroidClient(this, brokerUrl, clientId); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("username"); options.setPassword("password".toCharArray()); options.setCleanSession(true); try { IMqttToken token = client.connect(options); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to connect to MQTT broker", e); } } @Override protected void onHandleIntent(Intent intent) { // 在这里订阅主题、发布消息和处理接收到的消息 // ... // 订阅主题 String topic = "my/topic"; int qos = 1; try { IMqttToken token = client.subscribe(topic, qos); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to subscribe to topic: " + topic, e); } // 发布消息 String message = "Hello, MQTT!"; try { client.publish(topic, message.getBytes(), qos, false); } catch (MqttException e) { Log.e(TAG, "Failed to publish message: " + message, e); } } @Override public void onDestroy() { super.onDestroy(); try { IMqttToken token = client.disconnect(); token.waitForCompletion(); } catch (MqttException e) { Log.e(TAG, "Failed to disconnect from MQTT broker", e); } } } ``` 您还需要实现 `MqttCallback` 接口并在回调方法处理接收到的消息。例如: ```java client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { // 处理连接丢失事件 } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // 处理接收到的消息 String payload = new String(message.getPayload()); Log.d(TAG, "Received message: " + payload); } @Override public void deliveryComplete(IMqttDeliveryToken token) { // 处理消息发送完成事件 } }); ``` 在 `onDestroy()` 方法断开 MQTT 客户端与代理服务器的连接。 希望这些信息能对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值