android service 和其他服务一样,并没有实际运行的界面,它运行在android 后台。一般通过service为应用程序提供服务(比如,从Internet下载文件,控制音乐播放器等)。Service的生命周期要比activity简单的多,它只有三个阶段(创建服务、开始服务、销毁服务)。下面通过具体事例讲解android的service组件。

1.创建android工程

在Eclipse中创建android工程 android_service_one

2.创建Service

在android工程中,创建包com.example.service,并添加方法MyService。该方法继承与Service。该类用来展示服务的三个生命周期。

 

package com.example.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/*
 * 
 */
public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    //第一次打开时调用
    public void onCreate()
    {
        Log.d("MyService", "onCreate");
        super.onCreate();
    }
    //停止时调用
    public void onDestory()
    {
        Log.d("MySerVice", "onDestory");
        super.onDestroy();
    }
    //开始时调用
    public void onStart(Intent intent,int startId)
    {
        Log.d("MyService", "onStart");
        super.onStart(intent, startId);
    }
}
MyService

相关文章:

  • 2021-10-02
  • 2021-10-02
  • 2021-04-29
  • 2021-06-24
猜你喜欢
  • 2021-08-01
  • 2021-07-13
  • 2021-10-21
  • 2021-12-04
  • 2021-07-14
  • 2021-05-25
  • 2022-12-23
相关资源
相似解决方案