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

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

 

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

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

    实际添加了一行:spa

    <serviceandroid:name="MyService"></service>操作系统

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

     

    <Button事件

           android:id="@+id/btnStartService"ci

            android:layout_width="wrap_content"get

           android:layout_height="wrap_content"it

            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还会再运行,经过设置->应用程序->运行的程序或服务,可看到。

相关文章
相关标签/搜索