Service

AndroidManifest.xml(注册服务)

<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>
        
       <span style="color:#ff0000;"> <service android:name=".MyService"></service></span>
</application>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. 测试启动本地服务"
        android:textSize="25sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="startMyService"
            android:text="启动服务" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="stopMyService"
            android:text="停止服务" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2.  测试绑定本地服务"
        android:textSize="25sp" 
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="bindMyService"
            android:text="绑定服务" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="unbindMyService"
            android:text="解绑服务" />
    </LinearLayout>
</LinearLayout>

MainActivity.java

package com.example.l07_service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.l07_service.MyService.MyBinder;

public class MainActivity extends Activity {

	private ServiceConnection conn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	/**
	 * startMyService
	 */
	public void startMyService(View view) {
		Intent intent = new Intent(this, MyService.class);
		startService(intent);
		Log.i("startMyService", "startMyService");
		Toast.makeText(this, "启动服务成功!", 0).show();
	}

	/**
	 * stopMyService
	 */
	public void stopMyService(View view) {
		Intent intent = new Intent(this, MyService.class);
		stopService(intent);
		Log.i("stopMyService", "stopMyService");
		Toast.makeText(this, "停止服务成功!", 0).show();

	}

	/**
	 * bindMyService
	 */
	private MyService myService;
	public void bindMyService(View view) {
		Intent intent = new Intent(this, MyService.class);
		// 创建ServiceConnection对象--绑定服务必须使activity与服务相关联
		if (conn==null) {
			conn = new ServiceConnection() {
				@Override
				public void onServiceDisconnected(ComponentName name) {
					Log.i("onServiceDisconnected", "onServiceDisconnected");
				}
				
				@Override
				public void onServiceConnected(ComponentName name, IBinder service) {
					MyService.MyBinder binder = (MyBinder) service;
					myService = binder.getService();
					Log.i("onServiceConnected", "onServiceConnected");
				}
			};
//第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行。
 bindService(intent, conn, Context.BIND_AUTO_CREATE);
			Toast.makeText(this, "绑定服务成功!", 0).show();
		}
	}

	/**
	 * unbindMyService 后面的(不要反复的做)
	 */
	public void unbindMyService(View view) {
		if (conn != null) {
			// 解绑定Service
			unbindService(conn);
			conn = null;
			Toast.makeText(this, "解绑服务成功!", 0).show();
		} else {
			Toast.makeText(this, "还没有绑定服务成功!", 0).show();
		}
	}

	/**
	 * 在退出之前调用 后面的(不要反复的做)
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (conn != null) {
			// 解绑定Service
			unbindService(conn);
			conn = null;
		}
	}

}

MyService.java

package com.example.l07_service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
	//构造服务
	public MyService() {
		Log.i("MyService", "MyService()");
	}
	//创建服务
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i("onCreate", "onCreate");
	}
	//
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("onStartCommand", "onStartCommand()");
		
		return super.onStartCommand(intent, flags, startId);
	}
	//绑定服务--并且返回绑定对象,不然绑定失败
	@Override
	public IBinder onBind(Intent intent) {
		Log.i("onBind", "onBind()");
		return new MyBinder();
	}
	/*
	 * 自定义Binder
	 */
	public class MyBinder extends Binder {
		public MyService getService() {
			return MyService.this;
		}
	}
	
	//解绑服务
	@Override
	public boolean onUnbind(Intent intent) {
		Log.i("onUnbind", "onUnbind");
		return super.onUnbind(intent);
	}
	//销毁服务
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("onDestroy", "onDestroy");
	}
}


测试Service的生命周期:(直接copy)

 startService()

 第一次

 MyService()

onCreate()

onStartCommand()

后面的

onStartCommand()

 stopService()

 第一次:

 onDestroy()

 后面的:

 不做任何事, 不抛出异常

 bindService()

 第一次

 MyService()

onCreate()

onBind()

ServiceConnection对象: onServiceConnected()

后面的(不要反复的做)

ServiceConnection对象: onServiceConnected()

 unbindService()

 第一次

 MyService()

onCreate()

onBind()

ServiceConnection对象: onServiceConnected()

后面的(不要反复的做)

onUnbind()

onDestroy()



你可能感兴趣的:(Service)