Service:通过startService方式开启服务

来源:互联网 发布:node v4.5.0 x64.msi 编辑:程序博客网 时间:2024/05/20 13:04

1、Service的生命周期

service : 没有界面的Activity service是activity他大伯

1.第一次开启服务时会调用onCreate,onStart 方法会被调用
2.第二次第三次在开启服务,只会调用onStart方法。
3.onDestroy方法我们到设置中手动停止服务时,才会调用,服务就会被关闭
4.使用stopService方法可以关闭服务,onDestroy方法就会被执行。

注意:如果服务不stopservice会长期在后台运行

2、通过startService方式开启

1.写一个类继承Service,配置androidmanifest2.使用startService可以开启服务3.使用stopService可以停止服务

代码:

(1)在MainActivity中编写如下代码:

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);       }    //开启服务方法    public void startService(View v){        //创建一个Intent对象,指定开启的是哪个服务        Intent intent = new Intent(this,SimpleService.class);        //开启服务        startService(intent);    }    //关闭服务的方法    public void stopService (View vv){        //创建一个Intent对象,指定开启的是哪个服务        Intent intent = new Intent(this,SimpleService.class);        //关闭服务        stopService(intent);    }    }

(2)新建SimpleService.java,编写如下代码:

//定义了一个服务 ,配置androidmanifestpublic class SimpleService extends Service {    @Override    public IBinder onBind(Intent intent) {        return null;    }    //服务被开启调用    @Override    public void onCreate() {        System.out.println("生命周期中Oncreate方法调用");        super.onCreate();    }    @Override    public void onStart(Intent intent, int startId) {        System.out.println("生命周期中onStart方法调用");        super.onStart(intent, startId);    }    //内部也是调用onStart方法    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        System.out.println("生命周期中onStartCommand方法调用");        return super.onStartCommand(intent, flags, startId);    }    //服务被注销时调用    @Override    public void onDestroy() {        System.out.println("生命周期中onDestroy方法调用");        super.onDestroy();    }}

(3)在manifest.xml文件中的application节点下配置service:

<service android:name=".SimpleService"></service>
0 0