第143页
currentTime.setOnClickListener(new View.OnClickListener() { //为按钮增加单击事件监听器
public void onClick(View v) {
startService(new Intent(CurrentTimeActivity.this, CurrentTimeService.class));/启动服务
}
});
}
}
(4)修改AndroidManifest.xml文件,增加Activity和Service配置,其代码如下:
package="com.mingrisoft"
android:versionCode="1"
android:versionName="1.0" >
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
(5)启动应用程序,界面如图13.2所示。单击“当前时间”按钮,会在LogCat中显示格式化的当前时间,如图13.3所示。
图13.2 应用程序主界面
图13.3 LogCat输出结果
13.2.6 实例2:继承Service输出当前时间
例13.2 在Eclipse中创建Android项目,名称为13.2,实现继承Service在后台输出当前时间。(实例位置:光盘\TM\sl\13\13.2)
(1)修改res\layout目录中的main.xml布局文件,设置背景图片并添加一个按钮,然后设置按钮文字的内容、颜色和大小,其代码如下:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
android:orientation="vertical" >
android:id="@+id/current_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/current_time"
android:textColor="@android:color/black"
android:textSize="25dp" />
(2)创建CurrentTimeService类,它继承了Service类,并且重写了onBind()和onStartCommand()方法,其中onStartCommand()方法用于在后台输出当前时间,其代码如下:
public class CurrentTimeService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Time time = new Time(); //创建Time对象
time.setToNow(); //设置时间为当前时间
String currentTime = time.format("%Y-%m-%d %H:%M:%S"); //设置时间格式
Log.i("CurrentTimeService", currentTime); //记录当前时间
return START_STICKY;
}
}
注意: 此处使用的时间格式与Java API中SimpleDateFormat类有所不同。
(3)创建CurrentTimeActivity类,它继承了Activity类。在onCreate()方法中获得按钮控件并为其增加单击事件监听器。在监听器中,使用Intent启动服务,其代码如下:
public class CurrentTimeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); //设置页面布局
Button currentTime = (Button) findViewById(R.id.current_time); //通过ID值获得按钮对象
currentTime.setOnClickListener(new View.OnClickListener() { //为按钮增加单击事件监听器
public void onClick(View v) {
startService(new Intent(CurrentTimeActivity.this, CurrentTimeService.class));/启动服务
}
});
}
}
(4)修改AndroidManifest.xml文件,增加Activity和Service配置,其代码如下: