10天学通Android开发(2-2)-核心组件Service创建

有些程序不需要交互,在后台运行,并可长时间运行,不被操作系统杀死,这就是组件Service

 

  1. 声明Service,新建classMyService,扩展自Service

  2. AndroidManifest中配置, Application中添加Serivice,选择MySerivice

    实际添加了一行:

    <serviceandroid:name="MyService"></service>

  3. 添加二个按钮,启动Service和停止Service

     

    <Button

           android:id="@+id/btnStartService"

            android:layout_width="wrap_content"

           android:layout_height="wrap_content"

            android:text="启动Servive"/>

     

        <Button

           android:id="@+id/btnStopService"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

           android:text="停止Service" />

    4)代码中添加二按钮的定义:

private Button btnStartService,btnStopService;

  

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnStartService=(Button) findViewById(R.id.btnStartService);

        btnStopService=(Button) findViewById(R.id.btnStopService);

        

       

}

5)添加两按钮的监听事件,鼠标放红线处,可自动生成:

(1)btnStartService.setOnClickListener(this);

(2)public class MainActivity extendsActionBarActivity implements OnClickListener

(3)@Override

         publicvoid onClick(View v) {

                  //TODO Auto-generated method stub

                   

                  }

6) 具体onClick内容:

@Override

         publicvoid onClick(View v) {

                  //TODO Auto-generated method stub

                   switch(v.getId()){

                   case R.id.btnStartService:

                   

                   break;

        case R.id.btnStopService:

                   

                   break;

        default:

                break;

                  }

7)启动Service,需要定义Intent,:

private Intent serviceIntent;

并创建实例:

 serviceIntent=newIntent(this,MyService.class);

8) 在我们的Service重写二方法,创建和销毁:

@Override

         publicvoid onCreate(){

                  System.out.println("创建好了");

                  super.onCreate();

         }

        

         @Override

         publicvoid onDestroy(){

                  System.out.println("被销毁了");

                  super.onDestroy();

         }      

9) 当前Activity销毁,Service还会再运行,通过设置->应用程序->运行的程序或服务,可看到。


你可能感兴趣的:(android,service,操作系统,后台运行)