温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-06 07:57:10 来源:网络 阅读:348 作者:wanxl 栏目:移动开发

有些程序不需要交互,在后台运行,并可长时间运行,不被操作系统杀死,这就是组件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还会再运行,通过设置->应用程序->运行的程序或服务,可看到。


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI