Android中的intentservice

在Android的应用中,往往需要在执行主界面的操作时,如果要执行耗时的操作,那么应该是另外开线程的,或者是用async或者handler,今天发现其实也可以用android中的一个Intentservice去实现。下面例子讲解下。

1 例子中是一个文本框,当用户输入内容后,模拟slepp 10秒,这个时候要是不分离线程,操作的话,用户再点界面,就会死死地停在那里,甚至是出现提示,要强行CLOSE,代码如下:
Java代码 复制代码
  1. EditText input = (EditText) findViewById(R.id.txt_input);   
  2.  String strInputMsg = input.getText().toString();     
  3.  SystemClock.sleep(30000); // 30 seconds, pretend to do work   TextView result = (TextView) findViewById(R.id.txt_result); result.setText(strInputMsg + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis()));   
EditText input = (EditText) findViewById(R.id.txt_input);
 String strInputMsg = input.getText().toString();  
 SystemClock.sleep(30000); // 30 seconds, pretend to do work   TextView result = (TextView) findViewById(R.id.txt_result); result.setText(strInputMsg + " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis())); 



 
2 下面是使用IntentService
   首先,我们搞一个类SimpleIntentService,继承了IntentService
Java代码 复制代码
  1. public class SimpleIntentService extends IntentService {   
  2.     public static final String PARAM_IN_MSG = "imsg";   
  3.     public static final String PARAM_OUT_MSG = "omsg";   
  4.   
  5.     public SimpleIntentService() {   
  6.         super("SimpleIntentService");   
  7.     }   
  8.   
  9.     @Override  
  10.     protected void onHandleIntent(Intent intent) {   
  11.   
  12.         String msg = intent.getStringExtra(PARAM_IN_MSG);   
  13.         SystemClock.sleep(3000); // 30 seconds   
  14.         String resultTxt = msg + " "  
  15.             + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());   
  16.         Log.v("SimpleIntentService""Handling msg: " + resultTxt);   
  17.   
  18.         Intent broadcastIntent = new Intent();   
  19.         broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);   
  20.         broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);   
  21.         broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);   
  22.         sendBroadcast(broadcastIntent);   
  23.     }  
public class SimpleIntentService extends IntentService {
    public static final String PARAM_IN_MSG = "imsg";
    public static final String PARAM_OUT_MSG = "omsg";

    public SimpleIntentService() {
        super("SimpleIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        String msg = intent.getStringExtra(PARAM_IN_MSG);
        SystemClock.sleep(3000); // 30 seconds
        String resultTxt = msg + " "
            + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
        Log.v("SimpleIntentService", "Handling msg: " + resultTxt);

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
        sendBroadcast(broadcastIntent);
    }



   我们将跟主界面线程分离的操作都写在这里的ononHandleIntent中,这里首先通过
主线程传递的Intent中,获得用户文本框中输入的内容,放到变量msg中,然后
又建立一个Intent,把结果放到这个Intent中去,然后再sendBroadcast(broadcastIntent)广播出去,丢回给主线程。

3 在主线程中,这样启动:
 
Java代码 复制代码
  1. EditText input = (EditText) findViewById(R.id.txt_input);   
  2.        String strInputMsg = input.getText().toString();   
  3.   
  4.        Intent msgIntent = new Intent(this, SimpleIntentService.class);   
  5.        msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, strInputMsg);   
  6.        startService(msgIntent);  
 EditText input = (EditText) findViewById(R.id.txt_input);
        String strInputMsg = input.getText().toString();

        Intent msgIntent = new Intent(this, SimpleIntentService.class);
        msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, strInputMsg);
        startService(msgIntent);

 
4 同时,在主线程中,也要有一个receive接收
 
Java代码 复制代码
  1. public class ResponseReceiver extends BroadcastReceiver {   
  2.         public static final String ACTION_RESP = "com.mamlambo.intent.action.MESSAGE_PROCESSED";   
  3.         @Override  
  4.         public void onReceive(Context context, Intent intent) {   
  5.               
  6.             // Update UI, new "message" processed by SimpleIntentService   
  7.            TextView result = (TextView) findViewById(R.id.txt_result);   
  8.            String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);   
  9.            result.setText(text);   
  10.         }   
  11.            
  12.     }   
  13.   
  14.    
public class ResponseReceiver extends BroadcastReceiver {
        public static final String ACTION_RESP = "com.mamlambo.intent.action.MESSAGE_PROCESSED";
        @Override
        public void onReceive(Context context, Intent intent) {
           
            // Update UI, new "message" processed by SimpleIntentService
           TextView result = (TextView) findViewById(R.id.txt_result);
           String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
           result.setText(text);
        }
        
    }

 

  当然,要注册这个broadcastReceiver,
Java代码 复制代码
  1. public void onCreate(Bundle savedInstanceState) {   
  2.        super.onCreate(savedInstanceState);   
  3.        setContentView(R.layout.main);   
  4.           
  5.        IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);   
  6.        filter.addCategory(Intent.CATEGORY_DEFAULT);   
  7.        receiver = new ResponseReceiver();   
  8.        registerReceiver(receiver, filter);   
  9.    }  
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
        filter.addCategory(Intent.CATEGORY_DEFAULT);
        receiver = new ResponseReceiver();
        registerReceiver(receiver, filter);
    }

  可以看到,intent service还是比较清晰简单的,但至于性能方面,还是要继续学习,
迟点继续研究下这玩意哦  
  • 0
    点赞
  • 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、付费专栏及课程。

余额充值