Android开发入门之Service用法分析

本文实例讲述了Android中Service用法。分享给大家供大家参考,具体如下:

关于Service的讲解网上已经很多了,这里是关于自己通过写代码Service的一点体会 还有结合其他人对Service的一点总结

Service可以理解为一个隐形的Activity 但它又与Activity有些不同,首先Service是没界面,用户看不到 可交互的组件 级别是与Activity是差不多的

Service中定义了一系列和自身声明周期相关的方法:

onBind(...)是必须实现的方法,返回一个绑定接口给Service
onCreate(); 当Service第一次被创建时 由系统调用
onStart(...)当通过startService()方法调用启动Service时被调用
onDestroy();当Service不再使用,系统调用该方法....

本次代码分别有MainActivity,Java,MyService.java main.xml这几个重要文件 下面通过这几个文件对Service进行理解 见注释

老规矩 先开始布局 挺简单的 就是几个Button

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Service测试"
 android:gravity="center_horizontal"
 />
<Button
 android:id="@+id/startButton"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Start Service"
/>
<Button
 android:id="@+id/stopButton"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Stop Service"
/>
<Button
 android:id="@+id/bindButton"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Bind Service"
/>
<Button
 android:id="@+id/unBindButton"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Unbind Service"
/>
</LinearLayout>

布局效果图:

开始服务文件, MyService继承Service

public class MyService extends Service
{
 final static String TAG = "MyService";
 @Override
 public IBinder onBind(Intent intent)
 {
  Log.i(TAG,"OnBind()......");
  showInfo("Onbind()......");
  return null;
 }
 // Setvice创建时被调用
 @Override
 public void onCreate()
 {
  Log.i(TAG,"onCreate()......");
   showInfo("onCreate()......");
  super.onCreate();
 }
 //当客户调用startService()启动Service时被调用
 @Override
 public void onStart(Intent intent, int startId)
 {
  Log.i(TAG,"onStart()........");
  showInfo("onStart()........");
  super.onStart(intent, startId);
 }
 @Override
 public void onDestroy()
 {
  Log.i(TAG,"onDestroy()........");
  showInfo("onDestroy()........");
  super.onDestroy();
 }
 @Override
 public boolean onUnbind(Intent intent)
 {
  Log.i(TAG,"onUnbind()........");
  showInfo("onUnbind()........");
  return super.onUnbind(intent);
 }
 public void showInfo(String str)
 {
  Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 }
}

上面主要是Service中几个周期函数 这个MyService代表一个服务,当然在这里面我们在里面加什么实质性的东西,例如可以在

Onstart(...)函数里创建一个音乐播放器MediaPlayer 当服务被启动时播放音乐.....

你创建了Service  就跟你创建Activity一样 必须在Manifest里注册 下面开始注册

<!-- 增加的Service -->
<service android:name=".MyService">
<intent-filter >
 <action android:name="com.study.android.action.MY_SERVICE"/>
</intent-filter>
</service>

服务就这样 注册成功。光注册成功还没有完成任务哦......  还有启动服务,停止服务,绑定服务,解除绑定的服务

package com.study.android;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
 final static String ACTION = "com.study.android.action.MY_SERVICE";
 private Button startButton,stopButton;
 private Button bindButton,unbindButton;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  startButton = (Button)findViewById(R.id.startButton);
  stopButton = (Button)findViewById(R.id.stopButton);
  bindButton = (Button)findViewById(R.id.bindButton);
  unbindButton = (Button)findViewById(R.id.unBindButton);
  // 开启服务
  startButton.setOnClickListener(new OnClickListener()
 {
  @Override
  public void onClick(View v)
  {
   // 启动服务
   startService(buildIntent());
  }
 });
  //startButton按下后 周期函数执行顺序 onCreate()----->onStart()
  /******************************************/
  // 停止服务
  stopButton.setOnClickListener(new OnClickListener()
 {
  @Override
  public void onClick(View v)
  {
   stopService(buildIntent());
  }
 });
  //stopButton按下后 周期函数执行顺序 onDestroy()
   /******************************************/
  // 绑定服务
  bindButton.setOnClickListener(new OnClickListener()
 {
  @Override
  public void onClick(View v)
  {
   bindService(buildIntent(),conn,Service.BIND_AUTO_CREATE);
   /*第三个参数:如何创建service 一般是制定绑定时自动创建*/
  }
 });
  // bindButton 被按下后(当前服务已经stop掉)周期函数执行顺序 onCreate()------->onBind()
   /******************************************/
  // 接触绑定Service
  unbindButton.setOnClickListener(new OnClickListener()
 {
  @Override
  public void onClick(View v)
  {
   unbindService(conn);
  }
 });
  //unbindButton按下后 周期函数执行顺序onUnbind()------->onDestroy()
 }
 // 连接对象
 private ServiceConnection conn = new ServiceConnection()
 {
 @Override
 public void onServiceConnected(ComponentName name, IBinder service)
 {
   Log.i("SERVICE","连接服务成功!");
   showInfo("连接服务成功!");
 }
 @Override
 public void onServiceDisconnected(ComponentName name)
 {
  Log.i("SERVICE","服务连接断开!");
  showInfo("服务连接断开!");
 }
 };
 public Intent buildIntent()
 {
  Intent intent = new Intent();
  // 设置Intent属性 注意:这里action属性要与Manifest里服务对应
  intent.setAction(ACTION);
  return intent;
 }
 public void showInfo(String str)
 {
   Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
 }
}

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android Service组件使用技巧总结》、《Android编程之activity操作技巧总结》、《Android资源操作技巧汇总》、《Android文件操作技巧汇总》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android开发入门与进阶教程》、《Android视图View技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

(0)

相关推荐

  • Android开发中LayoutInflater用法详解

    本文实例讲述了Android开发中LayoutInflater用法.分享给大家供大家参考,具体如下: 在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化:而findViewById()是找xml布局文件下的具体widget控件(如Button.TextView等). 具体作用: 1.对于一个没有被载入或者想要动态载入的界面,都需要使用Layout

  • Android开发入门之Appwidget用法分析

    本文实例讲述了Android Appwidget用法.分享给大家供大家参考,具体如下: App Widgets 是一个小型应用程序的View  他可以嵌入到其他应用程序中(如 桌面程序) 并且可以得到周期性刷新. 在创建App Widget之前需要了解以下几个概念 AppWidgetProviderInfo对象 它是对App Widget 元数据的一个描述,譬如 AppWidget的布局,刷新频率,以及   AppWidgetProvider 类  这些元数据都是定义在XML中. AppWidg

  • Android开发入门之对话框简单用法

    本文实例讲述了Android开发入门之对话框简单用法.分享给大家供大家参考,具体如下: 注:本文只是一个学习笔记 用以记录自己学到哪了 1.获得AlertDialog的静态内部类Builder对象,由此类来创建对话框 2.通过Builder对象设置对话框的标题 按钮以及按钮响应的事件 3.调用Builder的Create()方法创建对话框 4.调用AlertDialog的show()方法显示对话框 main.xml文件 <?xml version="1.0" encoding=&

  • Android开发之获取LayoutInflater对象的方法总结

    本文实例讲述了Android开发之获取LayoutInflater对象的方法.分享给大家供大家参考,具体如下: 在写Android程序时,有时候会编写自定义的View,使用Inflater对象来将布局文件解析成一个View.本文主要目的是总结获取LayoutInflater对象的方法. 1.若能获取context对象,可以有以下几种方法: LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYO

  • 基于Android LayoutInflater的使用介绍

    在android中,LayoutInflater有点类似于Activity的findViewById(id),不同的是LayoutInflater是用来找layout下的xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等). 下面通过一个例子进行详细说明: 1.在res/layout文件夹下,添加一个xml文件dialog.xml 复制代码 代码如下: <LinearLayout xmlns:android=&qu

  • Android LayoutInflater中 Inflate()方法应用

    Android Inflate()方法的作用是将xml定义的一个布局找出来,但仅仅是找出来而且隐藏的,没有找到的同时并显示功能.最近做的一个项目就是这一点让我迷茫了好几天. Android上还有一个与Inflate()功能类似的方法叫findViewById(),二者有时可以互换使用,但也有区别: 如果你的Activity里用到别的layout,比如对话框layout,你还要设置这个layout上的其他组件的内容,你就必须用inflate()方法先将对话框的layout找出来,然后再用findV

  • Android开发入门之Notification用法分析

    本文实例讲述了Android中Notification用法.分享给大家供大家参考,具体如下: Notification可以理解为通知的意思一般用来显示广播信息 用Notification就必须要用到NotificationManager 想用Notification一般有三个步骤,如下所示 ① 一般获得系统级的服务NotificationManager. 调用Context.getSystemService(NOTIFICATION_SERVICE)方法即可返回NotificationManag

  • Android开发入门之Service用法分析

    本文实例讲述了Android中Service用法.分享给大家供大家参考,具体如下: 关于Service的讲解网上已经很多了,这里是关于自己通过写代码Service的一点体会 还有结合其他人对Service的一点总结 Service可以理解为一个隐形的Activity 但它又与Activity有些不同,首先Service是没界面,用户看不到 可交互的组件 级别是与Activity是差不多的 Service中定义了一系列和自身声明周期相关的方法: onBind(...)是必须实现的方法,返回一个绑定

  • Android开发之菜单(menu)用法实例分析

    本文实例讲述了Android开发之菜单(menu)用法.分享给大家供大家参考,具体如下: Android手机专门用一个按键"menu"来显示菜单. 要实现菜单功能,首先要通过方法onCreateOptionMenu来创建菜单,创建方法有两种:一种是直接导入有menu的xml文件,一种是用类Menu的方法直接添加.创建好菜单后,用事件监听器onOptionItemSelected对能够触发的事件进行监听. 下面这个例子有两个Activity,分别有上面的两种方法实现menu,每个menu

  • Android开发之软键盘用法实例分析

    本文实例讲述了Android开发中软键盘用法.分享给大家供大家参考.具体如下: 打开软键盘,有两个方法.一个是showSoftInput,一个是toggleSoftInput. package com.example.dd; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Menu; import android.view.View

  • Android桌面插件App Widget用法分析

    本文实例讲述了Android桌面插件App Widget用法.分享给大家供大家参考,具体如下: 应用程序窗口小部件App Widgets 应用程序窗口小部件(Widget)是微小的应用程序视图,可以被嵌入到其它应用程序中(比如桌面)并接收周期性的更新.你可以通过一个App Widget provider来发布一个Widget.可以容纳其它App Widget的应用程序组件被称为App Widget宿主.下面的截屏显示了一个音乐App Widget. appwidget 这篇文章描述了如何使用Ap

  • Android开发中ProgressDialog简单用法示例

    本文实例讲述了Android开发中ProgressDialog简单用法.分享给大家供大家参考,具体如下: 网上一般对进度条的示例都是如何显示,没有在任务结束如何关闭的文章,参考其他文章经过试验之后把整套进度条显示的简单示例如下: 建立android工程等工作都略去,Google一下就可以了. 下面来介绍主要的Activity ProgressBarDemo.java package com.lveyo.android.demo.progressbar; import android.app.Ac

  • Android编程中PopupWindow的用法分析【位置、动画、焦点】

    本文实例讲述了Android编程中popupwindow用法.分享给大家供大家参考,具体如下: 在Android中有很多级别的Window,不同级别的Window按照z-index方向分布.下面看看Android控件(view)PopupWindow的用法(位置.动画.焦点). 1.创建PopouWindow及相关参数设置 //创建一个包含自定义view的PopupWindow private PopupWindow makePopupWindow(Context cx) { PopupWind

  • Android开发之资源文件用法实例总结

    本文实例总结了Android开发之资源文件用法.分享给大家供大家参考,具体如下: 这里记录在Android开发中经常用到的一些用法 arrays.xml定义数组 例: <resources> <!-- share items --> <string-array name="app_share_items"> <item>新浪微博</item> <item>腾讯微博</item> </string-

随机推荐