本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


服务,就是跑在后台的“程序”,不需要和用户进行交互。举个例子,当使用一款应用的时候,可能同时想在后台播放一些音乐。在这种情况下,后来播放音乐的代码不需要和用户进行交互,所以,它就可能被当成一个服务。当不需要给用户提供UI的时候,服务也是一种非常好的选择。

想要彻底的了解服务的工作原理,最好的办法就是去着手尝试一下。下面将会新建一个简单的服务,并且在其中添加一些方法。讲述如何开启和关闭一个服务。

1. 新建一个工程,Services。

2. 新建一个类,MyService。

public class MyService extends Service {    @Override    public IBinder onBind(Intent arg0) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        // We want this service to continue running until it is explicitly        // stopped, so return sticky.        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();return START_STICKY;    }@Overridepublic void onDestroy() {super.onDestroy();Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();}}

3. 修改AndroidManifest.xml。

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="net.manoel.Services"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="14" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".ServicesActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                                           <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>                <service android:name=".MyService">            <intent-filter>                <action android:name="net.manoel.MyService" />            </intent-filter>        </service>            </application></manifest>

4. 修改main.xml。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><Button android:id="@+id/btnStartService"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="Start Service"     android:onClick="startService"/><Button android:id="@+id/btnStopService"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:text="Stop Service"    android:onClick="stopService" />    </LinearLayout>

5. 修改ServicesActivity.java。

public class ServicesActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);    }        public void startService(View view) {        startService(new Intent(getBaseContext(), MyService.class));    }        public void stopService(View view) {        stopService(new Intent(getBaseContext(), MyService.class));    }}
6. 调试


这个例子展示了最简单的服务。这个服务本身不会做什么有用的东西,只是显示服务创建的过程。

首先,定义一个Serivce基类的子类。所有的服务都继承Service基类。

public class MyService extends Service {}
然后,实现3个方法。

    @Override    public IBinder onBind(Intent arg0) { ... }    @Override    public int onStartCommand(Intent intent, int flags, int startId) { ... }@Overridepublic void onDestroy() { ... }

onBind()方法可以把一个activity绑定到一个service上面。这就是说,这个方法可以让一个activity去直接访问一个service里面的成员变量和方法。目前,仅仅返回一个null,后续再讨论这个方法。


onStartCommand()方法,在调用startService()的时候被调用。这个方法意味着service的开始,这里可以写一些自己的代码逻辑。这里,我返回了一个常量START_STICKY,这样的话,如果这个service不stop的话就会一直跑下去。


onDestroy()方法,在调用stopService()的时候被调用。这里可以清理service用到过的资源。

除了代码中的例子,也可以用另外一种方法去开启服务。

在AndroidManifest.xml中声明Action。

        <service android:name=".MyService">            <intent-filter>                <action android:name="net.manoel.MyService" />            </intent-filter>        </service>        

startService(new Intent("net.manoel.MyService"));

想要停止一个服务,调用stopService():

stopService(new Intent(getBaseContext(), MyService.class));



更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 如何在后台运行Linux命令?
  3. (转)Android中通过Intent 调用图片、视频、音频、录音、拍照
  4. Android登录Web以及登录保持和cookie的使用方法
  5. android中使用代码启动其他程序
  6. Android异步更新UI的方式之使用runOnUiThread(action)方法
  7. Android(安卓)读取excel (支持 xls和xlsx)
  8. android 数字进度条--NumberProgressBar
  9. 《Beginning Android(安卓)Games》给出基本框架的实现(1)

随机推荐

  1. Android应用开发之(让你的应用向后兼容)
  2. 2012-04-12 21:24 Android(安卓)开发中发
  3. Android(安卓)Toast自定义
  4. 利用Fiddler对Android模拟器网络请求进行
  5. AsyncTask的用法总结
  6. 从实际问题中分析 Android中@id与@+id区
  7. Android帧缓冲区(Frame Buffer)硬件抽象层(H
  8. [Android]如何做一个崩溃率少于千分之三
  9. Android(安卓)selector设置详解
  10. 【Android(安卓)Camera】 之 SmoothZoom