Service

来源:互联网 发布:沉迷于网络的危害 编辑:程序博客网 时间:2024/05/21 06:20

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;@Overrideprotected 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() {@Overridepublic void onServiceDisconnected(ComponentName name) {Log.i("onServiceDisconnected", "onServiceDisconnected");}@Overridepublic 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) {// 解绑定ServiceunbindService(conn);conn = null;Toast.makeText(this, "解绑服务成功!", 0).show();} else {Toast.makeText(this, "还没有绑定服务成功!", 0).show();}}/** * 在退出之前调用 后面的(不要反复的做) */@Overrideprotected void onDestroy() {super.onDestroy();if (conn != null) {// 解绑定ServiceunbindService(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()");}//创建服务@Overridepublic void onCreate() {super.onCreate();Log.i("onCreate", "onCreate");}//@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("onStartCommand", "onStartCommand()");return super.onStartCommand(intent, flags, startId);}//绑定服务--并且返回绑定对象,不然绑定失败@Overridepublic IBinder onBind(Intent intent) {Log.i("onBind", "onBind()");return new MyBinder();}/* * 自定义Binder */public class MyBinder extends Binder {public MyService getService() {return MyService.this;}}//解绑服务@Overridepublic boolean onUnbind(Intent intent) {Log.i("onUnbind", "onUnbind");return super.onUnbind(intent);}//销毁服务@Overridepublic void onDestroy() {super.onDestroy();Log.i("onDestroy", "onDestroy");}}


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

点击启动服务:

 第一次----构造方法、onCreate、onStartCommand

 MyService()

onCreate()

onStartCommand()


如果在次点击启动服务:

onStartCommand()


如果点击停止服务:

 第一次:

 onDestroy()


如果在次点击停止服务:

 不做任何事, 不抛出异常


如果第一次点击绑定服务--没有onStartCommand方法

 第一次

 MyService()

onCreate()

onBind()


ServiceConnection对象: onServiceConnected(


服务

 unbindService()

onUnbind()

onDestroy()



0 0
原创粉丝点击