Android的很多功能都使用到了后台服务,就像Windows应用程序大量依赖后台服务一样。服务的作用无需赘言,Android应用程序是如何实现后台服务的呢。今天写了一个创建和停止后台服务的简单例子,在此提供给大家做参考。当然Android后台服务的实际应用肯定比这个复杂,更为复杂的情况我们今后再做探讨。

ServiceActivity

<span style="font-family:Microsoft YaHei;">package com.example.androidexample;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class ServiceActivity extends Activity {private Button btnStartService;private Button btnStopService;private Intent intent;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);super.setContentView(R.layout.activity_service);intent = new Intent();intent.setAction("My_Action");btnStartService = (Button)super.findViewById(R.id.btnStartService);btnStopService = (Button)super.findViewById(R.id.btnStopService);btnStartService.setOnClickListener(startServiceListener);btnStopService.setOnClickListener(stopServiceListener);}OnClickListener startServiceListener = new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubstartService(intent);}};OnClickListener stopServiceListener = new OnClickListener(){@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubstopService(intent);}};}</span>
从这个Activity里我们注意到Activity和Service的关联是通过Intent实现的。通过设置Intent的Action来指定动作的执行者。这里还需要说的一点是关于Service的Manifest.xml配置文件。这里面需要指定Action和Service的类名。

<span style="font-family:Microsoft YaHei;"><application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.androidexample.ServiceActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>       <service android:name="com.example.business.FirstService">      <intent-filter>          <action android:name="My_Action"></action>      </intent-filter>  </service>    </application></span>

这里我们能够更加清楚地看到Activity是如何跟Service连接起来的。

我们使用的布局很简单,就是两个按钮。

<span style="font-family:Microsoft YaHei;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >     <Button             android:id="@+id/btnStartService"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="@string/StartService"/>    <Button             android:id="@+id/btnStopService"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:text="@string/StopService"/></LinearLayout></span>

这里还有一个重要的角色类不可忽视,那就是Service类。

<span style="font-family:Microsoft YaHei;">package com.example.business;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;import com.example.androidexample.*;public class FirstService extends Service {@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();System.out.println("Service is created.");//Toast.makeText(new ServiceActivity(), "Service is created", Toast.LENGTH_LONG).show();}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();System.out.println("Service is destoryed.");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {System.out.println("Service is started.");// TODO Auto-generated method stubreturn super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}}</span>
这个类很好理解,是做Service的启动和停止的。注意这里的System.out.println()不是往console里面输出,而是输出在LogCat的消息里面。


点击StartService 和 StopService后我再LogCat上能看到如下消息:


下一个章节我们会讨论

更多相关文章

  1. Android系统服务概要
  2. 在Android(安卓)Studio 编写应用程序,在模拟器中显示“我对Androi
  3. android上传图片至服务器
  4. Android(安卓)支持的文件类型
  5. Android(安卓)应用启动闪白一下处理方法
  6. Android(安卓)API 指南
  7. android (19)
  8. Android异步处理二:使用AsyncTask异步更新UI界面
  9. Android异步处理二:使用AsyncTask异步更新UI界面

随机推荐

  1. [gitbook] Android框架分析系列之Android
  2. Android电话秀(二)
  3. android ndk 入门2 - 基本方法实现
  4. 浅析Android中的消息机制
  5. Android(安卓)隐藏显示键盘
  6. 安卓报错:java.lang.RuntimeException: Un
  7. ListPreference
  8. Android(安卓)JB 4.2 中InputManager 启
  9. AndroidManifest.xml文件详解(service)
  10. 笔记——Android(安卓)中的小细节