`
uule
  • 浏览: 6337949 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

Android中服务service

 
阅读更多

什么时候需要Service呢?比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息位置的改变等等,总之服务嘛,总是藏在后头的。

Android开发中,当需要创建在后台运行的程序的时候,就要使用到Service。
每个服务都继承Service基类。

Service 特别需要注意的是Service跟Activities是不同的(简单来说可以理解为后台与前台的区别) 需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。

启动一个Service的过程如下
context.startService()  ->onCreate()- >onStart()->Service running
其中onCreate()可以进行一些服务的初始化工作,onStart()则启动服务。

停止一个Service的过程如下
context.stopService() | ->onDestroy() ->Service stop
 
Service是在一段不定的时间运行在后台,不和用户交互应用组件。每个Service必须在manifest中 通过<service>来声明。
可以通过contect.startservice和contect.bindserverice来启动
Service和其他的应用组件一样,运行在进程的主线程中。这就是说如果service需要很多耗时或者阻塞的操作,需要在其子线程中实现。

 

调用方式:

//1、
startService(new Intent(this, MyService.class));
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE); 
<service android:enabled="true" android:name=".MyService" />

//2、
startService(new Intent("com.demo.SERVICE_DEMO")); 
bindService(new Intent("com.demo.SERVICE_DEMO"),this.serviceConnection, BIND_AUTO_CREATE);
<service android:name=".LocalService">
        <intent-filter>
                <action android:name="com.demo.SERVICE_DEMO" />
                <category android:name="android.intent.category.default" />
        </intent-filter>
</service>
 

service的两种模式(startService()/bindService()不是完全分离的):
本地服务 Local Service 用于应用程序内部:
    它可以启动并运行,直至有人停止了它或它自己停止。在这种方式下,它以调用Context.startService()启动,而以调用Context.stopService()结束。它可以调用Service.stopSelf() 或 Service.stopSelfResult()来自己停止。不论调用了多少次startService()方法,你只需要调用一次stopService()来停止服务。
    用于实现应用程序自己的一些耗时任务,比如查询升级信息,并不占用应用程序比如Activity所属线程,而是单开线程后台执行,这样用户体验比较好。


远程服务 Remote Service 用于android系统内部的应用程序之间:
    它可以通过自己定义并暴露出来的接口进行程序操作。客户端建立一个到服务对象的连接,并通过那个连接来调用服务。连接以调用Context.bindService()方法建立,以调用 Context.unbindService()关闭。多个客户端可以绑定至同一个服务。如果服务此时还没有加载,bindService()会先加载它。
    可被其他应用程序复用,比如天气预报服务,其他应用程序不需要再写这样的服务,调用已有的即可。

两种启动Service的方式有所不同。这里要说明一下的是如果你在Service的onCreate或者onStart做一些很耗时间的事情,最好在 Service里启动一个线程来完成,因为Service是跑在主线程中,他也不是一个独立的线程,而是和main用一个线程。会影响到你的UI操作或者阻塞主线程中的其他事情。

但要注意,如果直接在service中直接启动另一个Activity则会出错。原因是没有设置flag,即在声明Intent的时候要设置flag:intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)。
服务不能自己运行 ,需要通过调用Context.startService()或Context.bindService()方法启动服务。这两个方法都可以启动Service,但是它们的使用场合有所不同。
    1. 使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。
    如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。   
    采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。


    2. 使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止 ,大有“不求同时生,必须同时死”的特点。
    onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。
    采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。

    官方文档告诉我们,一个service可以同时start并且bind,在这样的情况,系统会一直保持service的运行状态如果service已经 start了或者BIND_AUTO_CREATE标志被设置。如果没有一个条件满足,那么系统将会调用onDestory方法来终止service.所 有的清理工作(终止线程,反注册接收器)都在onDestory中完成。

生命周期
    Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法。

    而启动service,根据onStartCommand的返回值不同,有两个附加的模式:
    1. START_STICKY 用于显示启动和停止service。
    2. START_NOT_STICKY或START_REDELIVER_INTENT用于有命令需要处理时才运行的模式。

本地service
1.不需和Activity交互的本地服务

public class LocalService extends Service {

        private static final String TAG = "LocalService";

        @Override
        public IBinder onBind(Intent intent) {
                Log.i(TAG, "onBind");
                return null;
        }

        @Override
        public void onCreate() {
                Log.i(TAG, "onCreate");
                super.onCreate();
        }

        @Override
        public void onDestroy() {
                Log.i(TAG, "onDestroy");
                super.onDestroy();
        }

        @Override
        public void onStart(Intent intent, int startId) {
                Log.i(TAG, "onStart");
                super.onStart(intent, startId);
        }
}
 
public class ServiceActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.servicedemo);

                ((Button) findViewById(R.id.startLocalService)).setOnClickListener(
                                new View.OnClickListener(){

                                        @Override
                                        public void onClick(View view) {
                                                // TODO Auto-generated method stub
                                               startService(new Intent("com.demo.SERVICE_DEMO"));
                                        }  
                                });

                ((Button) findViewById(R.id.stopLocalService)).setOnClickListener(
                                new View.OnClickListener(){

                                        @Override
                                        public void onClick(View view) {
                                                // TODO Auto-generated method stub
                                                stopService(new Intent("com.demo.SERVICE_DEMO"));
                                        }
                                });
        }

}
 
<service android:name=".LocalService">
        <intent-filter>
                <action android:name="com.demo.SERVICE_DEMO" />
                <category android:name="android.intent.category.default" />
        </intent-filter>
</service>
 否则启动服务时会提示new Intent找不到"com.demo.SERVICE_DEMO"。

    对于这类不需和Activity交互的本地服务,是使用startService/stopService的最好例子。
    运行时可以发现第一次startService时,会调用onCreate和onStart,在没有stopService前,无论点击多少次startService,都只会调用onStart。而stopService时调用onDestroy。再次点击stopService,会发现不会进入service的生命周期的,即不会再调用onCreate,onStart和onDestroy。
    而onBind在startService/stopService中没有调用。

2.本地服务和Activity交互
    对于这种case,官方的sample(APIDemo\app.LocalService)是最好的例子:

/**
* This is an example of implementing an application service that runs locally
* in the same process as the application.    The {@link LocalServiceController}
* and {@link LocalServiceBinding} classes show how to interact with the
* service.
*
* <p>Notice the use of the {@link NotificationManager} when interesting things
* happen in the service.    This is generally how background services should
* interact with the user, rather than doing something more disruptive such as
* calling startActivity().
*/
public class LocalService extends Service {
        private NotificationManager mNM;

        /**
         * Class for clients to access.    Because we know this service always
         * runs in the same process as its clients, we don't need to deal with
         * IPC.
         */
        public class LocalBinder extends Binder {
                LocalService getService() {
                        return LocalService.this;
                }
        }
        
        @Override
        public void onCreate() {
                mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

                // Display a notification about us starting.    We put an icon in the status bar.
                showNotification();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
                Log.i("LocalService", "Received start id " + startId + ": " + intent);
                // We want this service to continue running until it is explicitly
                // stopped, so return sticky.
                return START_STICKY;
        }

        @Override
        public void onDestroy() {
                // Cancel the persistent notification.
                mNM.cancel(R.string.local_service_started);

                // Tell the user we stopped.
                Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
        }

        @Override
        public IBinder onBind(Intent intent) {
             return mBinder;
        }

        // This is the object that receives interactions from clients.    See
        // RemoteService for a more complete example.
        private final IBinder mBinder = new LocalBinder();

        /**
         * Show a notification while this service is running.
         */
        private void showNotification() {
                // In this sample, we'll use the same text for the ticker and the expanded notification
                CharSequence text = getText(R.string.local_service_started);

                // Set the icon, scrolling text and timestamp
                Notification notification = new Notification(R.drawable.stat_sample, text,
                                System.currentTimeMillis());

                // The PendingIntent to launch our activity if the user selects this notification
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                new Intent(this, LocalServiceController.class), 0);

                // Set the info for the views that show in the notification panel.
                notification.setLatestEventInfo(this, getText(R.string.local_service_label),
                                             text, contentIntent);

                // Send the notification.
                // We use a layout id because it is a unique number.    We use it later to cancel.
                mNM.notify(R.string.local_service_started, notification);
        }
}
 这里可以发现onBind需要返回一个IBinder对象。也就是说和上一例子LocalService不同的是,
1. 添加了一个public内部类继承Binder,并添加getService方法来返回当前的Service对象;
2. 新建一个IBinder对象——new那个Binder内部类;
3. onBind方法返还那个IBinder对象。

Activity:
public class LocalServiceBinding extends Activity {
        private boolean mIsBound;
        private LocalService mBoundService;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                setContentView(R.layout.local_service_binding);

                // Watch for button clicks.
                Button button = (Button)findViewById(R.id.bind);
                button.setOnClickListener(mBindListener);
                button = (Button)findViewById(R.id.unbind);
                button.setOnClickListener(mUnbindListener);
        }

        private ServiceConnection mConnection = new ServiceConnection() {
                public void onServiceConnected(ComponentName className, IBinder service) {
                        // This is called when the connection with the service has been
                        // established, giving us the service object we can use to
                        // interact with the service.    Because we have bound to a explicit
                        // service that we know is running in our own process, we can
                        // cast its IBinder to a concrete class and directly access it.
                        mBoundService = ((LocalService.LocalBinder)service).getService();  
                        
                        // Tell the user about this for our demo.
                        Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
                                        Toast.LENGTH_SHORT).show();
                }

                public void onServiceDisconnected(ComponentName className) { 
                        // This is called when the connection with the service has been
                        // unexpectedly disconnected -- that is, its process crashed.
                        // Because it is running in our same process, we should never
                        // see this happen.
                        mBoundService = null;
                        Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
                                        Toast.LENGTH_SHORT).show();
                }
        };

        private OnClickListener mBindListener = new OnClickListener() {
                public void onClick(View v) {
                        // Establish a connection with the service.    We use an explicit
                        // class name because we want a specific service implementation that
                        // we know will be running in our own process (and thus won't be
                        // supporting component replacement by other applications).
                        bindService(new Intent(LocalServiceBinding.this,    
                                        LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
                        mIsBound = true;
                }
        };

        private OnClickListener mUnbindListener = new OnClickListener() {
                public void onClick(View v) {
                        if (mIsBound) {
                                // Detach our existing connection.
                                unbindService(mConnection);
                                mIsBound = false;
                        }
                }
        };
}
 明显看出这里面添加了一个名为ServiceConnection类,并实现了onServiceConnected(从IBinder获取Service对象)和onServiceDisconnected(set Service to null)。
    而bindService和unbindService方法都是操作这个ServiceConnection对象的。
<service android:name=".app.LocalService" />

<activity android:name=".app.LocalServiceBinding" android:label="@string/activity_local_service_binding">
     <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.SAMPLE_CODE" />
     </intent-filter>
</activity>
本例来源:
可以参考下面例子:


Example2:
利用后台服务播放音乐的小例子,点击start运行服务,点击stop停止服务。


 
public class MyService extends Service {
        private static final String TAG = "MyService";
        MediaPlayer player;
        
        @Override
        public IBinder onBind(Intent intent) {
                return null;
        }
        
        @Override
        public void onCreate() {
                Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
                Log.d(TAG, "onCreate");
                
                player = MediaPlayer.create(this, R.raw.braincandy);//运行例子是,需要替换音乐的名称
                player.setLooping(false); // Set looping
        }

        @Override
        public void onDestroy() {
                Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
                Log.d(TAG, "onDestroy");
                player.stop();
        }
        
        @Override
        public void onStart(Intent intent, int startid) {
                Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
                Log.d(TAG, "onStart");
                player.start();
        }
}
 
public class ServicesDemo extends Activity implements OnClickListener {
  private static final String TAG = "ServicesDemo";
  Button buttonStart, buttonStop;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, MyService.class));
      break;
    }
  }
}
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ServicesDemo" 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:enabled="true" android:name=".MyService" />
  </application>
  <uses-sdk android:minSdkVersion="3" />
</manifest> 
 ...

 


  • 大小: 10.6 KB
分享到:
评论

相关推荐

    android学习之Service启动1

    在Android开发中,Service是四大组件之一,它用于在后台执行长时间运行的操作,而不与用户交互。本篇文章将深入探讨“android学习之Service启动1”的主题,主要关注Service的启动方式及其基本用法。 首先,Service...

    Android系统在新进程中启动自定义服务过程(startService)的原理

    "Android系统在新进程中启动自定义服务过程(startService)的原理" 在 Android 系统中,startService 函数是一个非常重要的函数,它允许开发者在新进程中启动自定义服务。这项技术可以将一些计算型逻辑从主进程中...

    Android 远程服务(remote service)

    在Android开发中,远程服务(Remote Service)是一种可以让应用程序组件在其他进程中运行的服务,通常用于实现跨进程通信(IPC,Inter-Process Communication)。这个概念是Android系统为了支持不同应用之间的数据...

    android demo,Service服务在android中的应用源代码。

    这个"android demo,Service服务在android中的应用源代码"是一个示例,展示了如何在Android应用程序中有效地使用Service组件。 在Android开发中,Service主要分为两种类型:Start Service和Bind Service。Start ...

    android service 简单实例源代码

    客户端通过`bindService()`方法连接到Service,并获取到Binder对象,从而能够调用Service中的方法: ```java private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void ...

    android 各种服务service练习

    在Android开发中,服务(Service)是四大组件之一,它在后台执行长时间运行的操作而无需与用户交互。本练习旨在帮助初学者深入理解和熟练运用Android中的各种服务类型及其使用场景。我们将通过一个示例项目来探讨...

    android 中的服务Service intentService例子

    在Android开发中,服务(Service)是用于在后台执行长时间运行操作的重要组件,不与用户界面直接交互。本文将深入探讨“Service”和其子类“IntentService”的使用,结合提供的标签“源码”和“工具”,我们将侧重于...

    如何创建android系统服务

    android系统级的服务包含了Android Service 和Native Service . Android Service 也称作 Java Service ,是用JAVA语言编写的,实现在框架层。 Native Service 也称作 System Service ,是用C++语言编写的,实现...

    Android Studio Service安卓在服务中如何弹出Dialog

    3. **在Service中使用Dialog**:在`Service`的适当位置,如`onStartCommand()`或`onCreate()`中,实例化并显示Dialog。确保在主线程中执行此操作,因为UI操作不应在子线程中进行。 ```java @Override public int ...

    Android 多个service的action 相同冲突 验证demo

    在Android开发中,Service是应用程序组件之一,用于在后台执行长时间运行的操作,即使用户与应用程序交互界面不直接关联。在某些情况下,我们可能需要启动多个Service来执行不同的任务,但问题在于,如果这些Service...

    Android之Service实现比较大小

    在Android开发中,Service是应用程序组件之一,用于在后台执行长时间运行的操作,即使用户与应用程序交互的界面已关闭。本篇文章将深入探讨Android中的Service,分析不同类型的Service及其特性,并对比它们之间的...

    android 录音机 service 例子

    为了监听录音状态,可以使用BroadcastReceiver,在Service中发送自定义广播,接收器接收到广播后更新UI或执行其他操作。 4. **权限管理** 录音功能需要申请相应的权限,需要在AndroidManifest.xml中添加`...

    Qt on Android 启动Android服务并通过该服务发射Qt信号

    2. **Android服务(Service)**:在Android系统中,服务是一种在后台运行的组件,不提供用户界面,但可以执行长时间运行的操作或为其他应用组件提供功能。在本例中,我们创建一个服务来监听SD卡的插入事件。 3. **...

    android如何绑定service

    1. Binder:`Binder`是Android系统提供的进程间通信(IPC)机制,使得客户端可以在自己的进程中调用Service中的方法。在Service中,你需要创建一个实现了`Binder`的类,然后在`onBind()`中返回这个Binder实例。 2. ...

    Music_Player_Service.rar_ANDROID 播放_Service android_android serv

    在Android开发中,服务(Service)是一个至关重要的组件,它允许应用程序在后台执行长时间运行的操作,而无需与用户界面交互。本项目“Music Player Service”是针对Android平台设计的一个音乐播放器,它深入展示了...

    Android-Service与Activity传值

    3. **Service中的数据处理** 在`MyService`的`onStartCommand()`方法中,可以通过`Intent`获取传递的数据: ```java @Override public int onStartCommand(Intent intent, int flags, int startId) { String ...

    android音乐播放器service学习案例

    在Android开发中,服务(Service)是一个至关重要的组件,它允许应用程序在后台执行长时间运行的操作,即使用户没有与应用交互。本案例“android音乐播放器service学习案例”着重讲解如何利用Service来实现一个音乐...

    Android中Service源码下载

    本资源提供了关于Android中Service的源码,重点展示了Service的生命周期以及如何在Service中播放音乐。通过分析和学习这个`ServiceTest`项目,我们可以深入理解Service的工作原理和用法。 首先,Service的生命周期...

Global site tag (gtag.js) - Google Analytics