Android IntentService使用

本文介绍如何使用Android的IntentService创建一个服务,该服务能够输出当前时间。通过继承IntentService并重写onHandleIntent方法,可以实现简单的后台任务处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为多数启动服务不必同时处理多个请求(在多线程情景下会很危险),所以使用IntentService类实现服务是很好的选择。本经验将通过继承IntentService输出当前时间教大家如何使用IntentService。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.basillee.asus.demo.MainActivity5">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="当前时间"
        android:id="@+id/button_current_time"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

  然后我们在编写一个CurrentTimeService类,继承IntentService

package com.basillee.asus.demo;
import android.app.IntentService;
import android.content.Intent;
import android.text.format.Time;
import android.util.Log;
public class CurrentTimeService extends IntentService {
    public CurrentTimeService(){
        super("CurrentTimeService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Time time=new Time();
        time.setToNow();
        String currentTime=time.format("%Y-%m-%d %H:%M:%S");
        Log.i("CurrentTimeService",currentTime);
    }
}

  然后我们在Oncreate方法里面编写如下代码为button增加监听事件

package com.basillee.asus.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity5 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity5);
        Button button= (Button) findViewById(R.id.button_current_time);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(MainActivity5.this, CurrentTimeService.class));
            }
        });
    }
}

  更多细节请看: http://jingyan.baidu.com/season/48891

转载于:https://www.cnblogs.com/BasilLee/p/4288045.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值