安卓-IntentService使用

有了Service为什么还要有个IntentService呢?

原因如下:

1)Service默认运行在主线程中,IntentService运行在一个新的线程中

2)Service需要主动调用stopSelf()或stopService()服务才可以停止,IntentService运行完后自动停止

使用IntentService需要注意2点:

1)构造函数中一定要调用父类的有参构造函数

2)需要耗时处理的事情放在onHandleIntent(Intent intent) 函数中

下面通过一个demo简单演示下IntentService的使用。服务中的几个关键函数均加入了日志,通知打印的线程id.测试结果如下:

02-18 14:11:22.186 26979-26979/com.mobile.cdtx.blog I/IntentServiceActivity: 主线程id: 1
02-18 14:11:22.196 26979-26979/com.mobile.cdtx.blog I/MyIntentService: MyIntentService: 
02-18 14:11:22.196 26979-26979/com.mobile.cdtx.blog I/MyIntentService: 构造函数服务线程id:1
02-18 14:11:22.196 26979-26979/com.mobile.cdtx.blog I/MyIntentService: onCreate: 
02-18 14:11:22.196 26979-26979/com.mobile.cdtx.blog I/MyIntentService: onStartCommand: 
02-18 14:11:22.196 26979-28547/com.mobile.cdtx.blog I/MyIntentService: 服务线程id:7012
02-18 14:11:22.216 26979-26979/com.mobile.cdtx.blog I/MyIntentService: onDestroy: 

说明:主线程id:1表示主线程id的编号为1,服务线程id:6961说明onHandleIntent(Intent intent)是一个新的线程;

         onDestroy说明执行完onHandleIntent(Intent intent)方法后自动停止了服务;

         构造函数服务线程id:1说明服务线程默认和主线程是一个线程;

         onBind方法默认返回null.

下面贴下测试代码:

布局文件activity_intent_service..xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_intent_service"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/id_btn_intentservice"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="启动IntentService"/>
</LinearLayout>

主活动代码:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.mobile.cdtx.blog.R;
import com.mobile.cdtx.blog.main.service.MyIntentService;

public class IntentServiceActivity extends AppCompatActivity {
    private static final String TAG = "IntentServiceActivity";
    Button btnIntentService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
        btnIntentService = (Button)findViewById(R.id.id_btn_intentservice);
        btnIntentService.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                startIntentService();
            }
        });
    }

    //启动IntentService
    private void startIntentService(){
        Log.i(TAG, "主线程id: " + Thread.currentThread(). getId());
        Intent intentService = new Intent(this, MyIntentService.class);
        startService(intentService);
    }
}
继承自IntentService类的服务代码:

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";
    public MyIntentService() {
        super("MyIntentService");
        Log.i(TAG, "MyIntentService: ");
        Log.i(TAG, "构造函数服务线程id:" + Thread.currentThread(). getId());
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return super.onBind(intent);
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: ");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.i(TAG, "onRebind: ");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // 打印当前线程的id
        Log.i(TAG, "服务线程id:" + Thread.currentThread(). getId());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }
}

最后不要忘记服务要在AndroidManifest.xml中注册

<service
            android:name=".main.service.MyIntentService"
            android:exported="false">
</service>





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值