Service学习之一--------服务生命周期

来源:互联网 发布:mac 删除文件夹的命令 编辑:程序博客网 时间:2024/05/20 10:24

1、要使用服务,第一件事是自己创建一个类继承Seivice:

package com.example.studyservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service {private static final String TAG = "Service";@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onCreate() {super.onCreate();Log.i(TAG, "onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(TAG, "onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.i(TAG, "onDestroy");}}


2、在MainActivity里面调用:

package com.example.studyservice;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void StartService(View view) {Intent service = new Intent();service.setClass(this, MyService.class);startService(service);}public void StopService(View view) {stopService(new Intent(this, MyService.class));}}

 当服务开启的时候走的是:

onCreate() -------> onStartCommand;


当停止服务的时候,在上面的基础上走onDestroy()



(3)记得在manifest注册:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.studyservice"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="19"        android:targetSdkVersion="21" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name="com.example.studyservice.MyService" />    </application></manifest>


0 0
原创粉丝点击