zoukankan      html  css  js  c++  java
  • Android应用开发基础篇(6)Service

    一、概述

           我们知道,Service是Android的四大组件之一。在我看来,Service可以理解为一种在后台运行的服务,但它不是运行在一个独立的线程中,而是运行在主线程里,当程序有比较“繁重”的任务要执行时,就可以把它放在Service中执行。Service也有自己的生命周期,与Activity有点类似,但它没有用户界面,只在后台运行。

    二、要求

           编写一个带有Service的程序,在程序中,用户可以启动和停止该服务,可以实现与Service之间的通信。

    三、实现

         新建工程MyService,修改/res/layout/main.xml文件,在里面添加3个Button按钮和1个TextView文本,完整的main.xml文件如下:

     1 <?xml version="1.0" encoding="utf-8"?>
    2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3 android:layout_width="fill_parent"
    4 android:layout_height="fill_parent"
    5 android:orientation="vertical" >
    6
    7 <Button
    8 android:id="@+id/button"
    9 android:layout_width="fill_parent"
    10 android:layout_height="wrap_content"
    11 android:text="启动服务"
    12 android:textSize="15px"
    13 />
    14
    15 <Button
    16 android:id="@+id/sbutton"
    17 android:layout_width="fill_parent"
    18 android:layout_height="wrap_content"
    19 android:text="停止服务"
    20 android:textSize="15px"
    21 />
    22
    23 <Button
    24 android:id="@+id/gbutton"
    25 android:layout_width="fill_parent"
    26 android:layout_height="wrap_content"
    27 android:text="获取服务信息"
    28 android:textSize="15px"
    29 />
    30
    31 <View
    32 android:layout_width="fill_parent"
    33 android:layout_height="70px"
    34 />
    35
    36 <TextView
    37 android:id="@+id/mtextview"
    38 android:layout_width="fill_parent"
    39 android:layout_height="wrap_content"
    40 android:gravity="center_horizontal"
    41 android:textSize="20px"
    42 android:textColor="#0000FF"
    43 />
    44
    45 </LinearLayout>

    新建MyService.java文件,编写一个继承自Service的MyService类,在该类中编写一个继承自Binder的MyBinder类,用来与Client之间的通信,在MyBinder类中编写一个reTurnService()方法,用来返回信息给Client,完整的

    MyService.java文件如下:

     1 package com.nan.service;
    2
    3 import android.app.Service;
    4 import android.content.Intent;
    5 import android.os.Binder;
    6 import android.os.IBinder;
    7 import android.util.Log;
    8
    9 public class MyService extends Service
    10 {
    11 final String TAG = "MyService";
    12
    13 MyBinder mMyBinder = new MyBinder();
    14
    15 @Override
    16 public IBinder onBind(Intent arg0)
    17 {
    18 // TODO Auto-generated method stub
    19 //返回对象给Client
    20 return mMyBinder;
    21 }
    22
    23 @Override
    24 public boolean onUnbind(Intent intent)
    25 {
    26
    27 return true;
    28 }
    29
    30 @Override
    31 public void onCreate()
    32 {
    33 super.onCreate();
    34 Log.v(TAG, "++ onCreate() ++");
    35 }
    36
    37 @Override
    38 public int onStartCommand(Intent intent, int flags, int startId)
    39 {
    40 super.onStartCommand(intent, flags, startId);
    41 Log.v(TAG, "++ onStartCommand() ++");
    42 return flags;
    43 }
    44
    45 @Override
    46 public void onDestroy()
    47 {
    48 super.onDestroy();
    49 Log.v(TAG, "++ onDestroy() ++");
    50 }
    51
    52 //自己定义一个继承自Binder的类
    53 public class MyBinder extends Binder
    54 {
    55 //返回Service中的信息
    56 public String reTurnService()
    57 {
    58 return "This String is from Servive!";
    59 }
    60 }
    61
    62 }

    接着,修改MyServiceActivity.java文件,定义1个MyService.MyBinder对象和1个ServiceConnection对象,实现
    ServiceConnection中的onServiceConnected()方法,该方法在bindService()后自动被调用,接收MyService传来的Binder对象。其他内容在程序中有详细注释,完整的MyServiceActivity.java文件如下:

      1 package com.nan.service;
    2
    3 import com.nan.service.MyService.MyBinder;
    4 import android.app.Activity;
    5 import android.content.ComponentName;
    6 import android.content.Intent;
    7 import android.content.ServiceConnection;
    8 import android.os.Bundle;
    9 import android.os.IBinder;
    10 import android.view.View;
    11 import android.widget.Button;
    12 import android.widget.TextView;
    13
    14
    15 public class MyServiceActivity extends Activity
    16 {
    17 private Button mButton = null;
    18 private Button sButton = null;
    19 private Button gButton = null;
    20 private TextView mTextView = null;
    21 //定义一个MyBinder对象
    22 private MyService.MyBinder mBinder;
    23 //定义一个ServiceConnection对象
    24 private ServiceConnection mServiceConnection;
    25 private Intent mIntent = new Intent();
    26
    27 /** Called when the activity is first created. */
    28 @Override
    29 public void onCreate(Bundle savedInstanceState)
    30 {
    31 super.onCreate(savedInstanceState);
    32 setContentView(R.layout.main);
    33
    34 mButton = (Button)findViewById(R.id.button);
    35 sButton = (Button)findViewById(R.id.sbutton);
    36 gButton = (Button)findViewById(R.id.gbutton);
    37 mTextView = (TextView)findViewById(R.id.mtextview);
    38
    39 //设置按钮动作处理
    40 mButton.setOnClickListener(new View.OnClickListener()
    41 {
    42
    43 @Override
    44 public void onClick(View v)
    45 {
    46 // TODO Auto-generated method stub
    47 //设置要启动Service类
    48 mIntent.setClass(MyServiceActivity.this, MyService.class);
    49 //绑定(建立)这个Service
    50 bindService(mIntent,mServiceConnection,BIND_AUTO_CREATE);
    51 }
    52 });
    53
    54 sButton.setEnabled(false);
    55 //设置按钮动作处理
    56 sButton.setOnClickListener(new View.OnClickListener()
    57 {
    58
    59 @Override
    60 public void onClick(View v)
    61 {
    62 // TODO Auto-generated method stub
    63 //取消与Service的连接
    64 unbindService(mServiceConnection);
    65 mButton.setEnabled(true);
    66 sButton.setEnabled(false);
    67 gButton.setEnabled(false);
    68 }
    69 });
    70
    71 gButton.setEnabled(false);
    72 //设置按钮动作处理
    73 gButton.setOnClickListener(new View.OnClickListener()
    74 {
    75
    76 @Override
    77 public void onClick(View v)
    78 {
    79 // TODO Auto-generated method stub
    80 //显示从Service传回来的信息
    81 mTextView.setText(mBinder.reTurnService());
    82 }
    83 });
    84
    85 //与Handler类的使用类似
    86 mServiceConnection = new ServiceConnection()
    87 {
    88
    89 @Override
    90 //当与Service建立连接后,这个函数自动被调用
    91 public void onServiceConnected(ComponentName name, IBinder service)
    92 {
    93 // TODO Auto-generated method stub
    94 //获得从Service传来IBinder对象
    95 mBinder = (MyBinder) service;
    96 sButton.setEnabled(true);
    97 mButton.setEnabled(false);
    98 gButton.setEnabled(true);
    99 }
    100
    101 @Override
    102 //当与Service断开连接后,这个函数自动被调用
    103 public void onServiceDisconnected(ComponentName name)
    104 {
    105 // TODO Auto-generated method stub
    106
    107 }
    108
    109 };
    110
    111 }
    112
    113 }

    最后,在AndroidManifest.xml文件,在里面添加一个Service声明,如下:

    <service android:name=".MyService" android:exported="true" />

    运行该程序:

    点击一下“启动服务”按钮:

    再点击“获取服务信息”按钮,会显示一串字符串,说明已经从Service中获取到了信息:

    点击“停止服务”按钮:

    完成。












  • 相关阅读:
    AGC037F Counting of Subarrays
    AGC025F Addition and Andition
    CF506C Mr. Kitayuta vs. Bamboos
    AGC032D Rotation Sort
    ARC101F Robots and Exits
    AGC032E Modulo Pairing
    CF559E Gerald and Path
    CF685C Optimal Point
    聊聊Mysql索引和redis跳表
    什么是线程安全
  • 原文地址:https://www.cnblogs.com/lknlfy/p/2360336.html
Copyright © 2011-2022 走看看