因为多数启动服务不必同时处理多个请求(在多线程情景下会很危险),所以使用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

更多相关文章

  1. Android(安卓)设备管理器和有权查看使用情况的应用详解
  2. Android资源文件xml的编写
  3. 读取android手机流量信息
  4. Android(安卓)ContentProvider实现应用间数据共享
  5. Android(安卓)获取当前设备的IP地址
  6. android项目源码异步加载远程图片的小例子
  7. Android(安卓)ApiDemos示例解析(15):App->Activity->SetWallpaper
  8. Android遍历某个文件夹的图片并实现滑动查看的的Gallery
  9. 【Android】使用ConnectivityManager与NetworkInfo实现判断当前

随机推荐

  1. mysql中文乱码彻底解决
  2. 远程连接Linux虚拟机上的mysql失败的解决
  3. MySQL 主从同步Out of Memory 错误分析
  4. MySQL数据库8(二十)视图
  5. CentOS7安装MySQL5.7遇到的若干问题记录
  6. 如何将数据从MYsql服务器传输到iphone
  7. 显示mysql表中的所有数据
  8. MySQL数据类型中DECIMAL的作用和用法
  9. mysql莫名问题 ERROR 1045 (28000): Acce
  10. oracle和mysql的几点重要区别总结