/**以下内容主要来源于android-sdk-windows/docs**/

services

  • Started Service
  • Bound Service
线程模型 A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). 在manifest文件中声明services
<manifest ... >  ...  <application ... >      <service android:name=".ExampleService" />      ...  </application></manifest>

Started Service
可以从 Service或者 IntentService继承,IntentService从Service继承,内部使用了一个工作线程和队列串行处理请求,如果对并发请求要求不高的话,推荐使用IntentService

启动一个服务,当调用 startService时,系统会调用服务的 onStartCommand
Intent intent = new Intent(this, HelloService.class);startService(intent);
如果希望获取结果,可使用 PendingIntent(for a broadcast)
继承IntentService实现服务:
public class HelloIntentService extends IntentService {  /**    * required   */  public HelloIntentService() {      super("HelloIntentService");  }  /**   *当启动服务后,该方法在一个默认的工作线程中执行,当这个方法返回时,服务自动停止.    */  @Override  protected void onHandleIntent(Intent intent) {      // Normally we would do some work here, like download a file.      // For our sample, we just sleep for 5 seconds.      long endTime = System.currentTimeMillis() + 5*1000;      while (System.currentTimeMillis() < endTime) {          synchronized (this) {              try {                  wait(endTime - System.currentTimeMillis());              } catch (Exception e) {              }          }      }  }@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    //my    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();    //基类的一定要调用    return super.onStartCommand(intent,flags,startId);}}
继承Service实现服务:
public class HelloService extends Service {  private Looper mServiceLooper;  private ServiceHandler mServiceHandler;  // Handler that receives messages from the thread  private final class ServiceHandler extends Handler {      public ServiceHandler(Looper looper) {          super(looper);      }      @Override      public void handleMessage(Message msg) {          // Normally we would do some work here, like download a file.          // For our sample, we just sleep for 5 seconds.          long endTime = System.currentTimeMillis() + 5*1000;          while (System.currentTimeMillis() < endTime) {              synchronized (this) {                  try {                      wait(endTime - System.currentTimeMillis());                  } catch (Exception e) {                  }              }          }          // Stop the service using the startId, so that we don't stop          // the service in the middle of handling another job          stopSelf(msg.arg1);      }  }  @Override  public void onCreate() {    // 创建一个工作线程    // Start up the thread running the service.  Note that we create a    // separate thread because the service normally runs in the process's    // main thread, which we don't want to block.  We also make it    // background priority so CPU-intensive work will not disrupt our UI.    HandlerThread thread = new HandlerThread("ServiceStartArguments",            Process.THREAD_PRIORITY_BACKGROUND);    thread.start();        // Get the HandlerThread's Looper and use it for our Handler     mServiceLooper = thread.getLooper();    mServiceHandler = new ServiceHandler(mServiceLooper);  }  @Override  public int onStartCommand(Intent intent, int flags, int startId) {      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();      // For each start request, send a message to start a job and deliver the      // start ID so we know which request we're stopping when we finish the job      Message msg = mServiceHandler.obtainMessage();      msg.arg1 = startId;      mServiceHandler.sendMessage(msg);            // If we get killed, after returning from here, restart      return START_STICKY;  }  @Override  public IBinder onBind(Intent intent) {      // We don't provide binding, so return null      return null;  }    @Override  public void onDestroy() {    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();   }}
注意 onStartCommand的返回值,决定当服务被杀掉后,系统怎么处理请求
  • START_NOT_STICKY
  • START_STICKY
  • START_REDELIVER_INTENT

停止服务 stopSelf(int startId) 如果startId和 最近一次 onStartCommand(Intent, int, int startId )的startId相同则停止服务。 stopService()

更多相关文章

  1. HandlerTest
  2. Android与服务器http连接模块代码
  3. android下多线程下载,断点续传,及暂停按钮
  4. Android(安卓)浅析 RxJava (一) 使用
  5. Handler+Thread+Message模式 Android线程网络
  6. Android(安卓)工具类
  7. android 多线程下载文件案例
  8. android_service_totoal
  9. Android中的数据库操作(保证线程安全)

随机推荐

  1. 多种方式实现Android定时任务,哪一款是你
  2. android中布局 padding gravity margin的
  3. UI(一) 适应屏幕设备多样化
  4. 五个维度:Android内存管理、优化
  5. [Android初级]android与netty4初体验
  6. Android云通信IM系列(1)-集成与配置
  7. Kivy A to Z -- 调试篇之在Android平台调
  8. Flutter教程(一) 十分钟了解Flutter
  9. android中json数据的解析
  10. android app中如何获取电源锁保持屏幕常