android service 用法

来源:互联网 发布:java接口压力测试工具 编辑:程序博客网 时间:2024/05/16 12:25
有问题请加:Q群: 241359063  共同走向创业学习之旅。
原创:kylin_zeng  http://blog.chinaunix.net/uid/23795897.html在此感谢mars 老师的帮助。
转载请注明原创出处,尊重他人的劳动成果。


1、service,是一个应用程序组件,跟activity比,它是一个不可见的,没有图形化界面。它常用来处理一些比较耗时的操作,比如下载,播放音乐等。也可以使用service 更新ContenProvider,发送Intent以及启动系统的通知,它是一直运行的,知道你关闭它。
2、service 不是一个单独的进程,也不是一个线程。
3、在AndroidManifest.xml 设置:

点击(此处)折叠或打开

  1. <application android:icon="@drawable/icon" android:label="@string/app_name">
  2.         <activity android:name=".TestActivity"
  3.                   android:label="@string/app_name">
  4.             <intent-filter>
  5.                 <action android:name="android.intent.action.MAIN" />
  6.                 <category android:name="android.intent.category.LAUNCHER" />
  7.             </intent-filter>
  8.         </activity>
  9.         <service android:name=".FirstService"></service>        //声明服务
  10.     </application>

4、做一个activity ,两个按钮,启动和停止服务。

点击(此处)折叠或打开

  1. package mars.service1;

  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;

  8. public class TestActivity extends Activity {
  9.     /** Called when the activity is first created. */
  10.     private Button startServiceButton = null;
  11.     private Button stopServiceButton = null;

  12.     @Override
  13.     public void onCreate(Bundle savedInstanceState) {
  14.         super.onCreate(savedInstanceState);
  15.         setContentView(R.layout.main);
  16.         startServiceButton = (Button) findViewById(R.id.startService);
  17.         startServiceButton.setOnClickListener(new StartServiceListener());
  18.         stopServiceButton = (Button) findViewById(R.id.stopService);
  19.         stopServiceButton.setOnClickListener(new StopServiceListener());
  20.         System.out.println("Activity onCreate");
  21.     }

  22.     class StartServiceListener implements OnClickListener {
  23.         @Override
  24.         public void onClick(View v) {
  25.             Intent intent = new Intent();
  26.             intent.setClass(TestActivity.this, FirstService.class);  
  27.             startService(intent);  //开启服务。
  28.         }
  29.     }

  30.     class StopServiceListener implements OnClickListener {
  31.         @Override
  32.         public void onClick(View v) {
  33.             Intent intent = new Intent();
  34.             intent.setClass(TestActivity.this, FirstService.class);
  35.             stopService(intent);   //停止服务。
  36.         }
  37.     }
  38. }

5、服务:

点击(此处)折叠或打开

  1. package mars.service1;

  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;

  6. public class FirstService extends Service {

  7.     @Override
  8.     public IBinder onBind(Intent intent) {
  9.         // TODO Auto-generated method stub
  10.         System.out.println("Service onBind");
  11.         return null;
  12.     }

  13.     //当创建一个Servcie对象之后,会首先调用这个函数,如果没有关闭服务,那么再次点击开启服务按钮时,不会再进入这个onCreate,因为之前的服务孩子
  14.     @Override
  15.     public void onCreate() {
  16.         // TODO Auto-generated method stub
  17.         super.onCreate();
  18.         System.out.println("Service onCreate");
  19.     }
  20.     
  21.     //onCreate后,就运行下面的工作。
  22.     @Override
  23.     public int onStartCommand(Intent intent, int flags, int startId) {
  24.         // TODO Auto-generated method stub
  25.         System.out.println("flags--->" + flags);        //flags =0 
  26.         System.out.println("startId--->" + startId);   //第二次点击开启服务时,startId 就加1
  27.         System.out.println("Service onStartCommand");
  28.         return START_NOT_STICKY;
  29.     }

  30.     //点击停止按钮时,就调用这个函数。
  31.     @Override
  32.     public void onDestroy() {
  33.         // TODO Auto-generated method stubo
  34.         System.out.println("Service onDestory");
  35.         super.onDestroy();
  36.     }
  37. }
mars视频教程ppt和代码01_25_src_ppt.zip


*****************************************************************
二、Bound service:

1、service 是一种组件,在后台处理一些比较耗时的操作,它没有用户界面,用户只能通过activity向service发送命令。
2、Bound service 和Start Service区别。Start service 无法向 activity返回数据。而Bound service则可以解决这个。

以下转载:http://blog.csdn.net/zoneyoung/article/details/13000789

3、在AndroidManifest.xml 注册

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="com.marschen.s01e26_service01"
  4.     android:versionCode="1"
  5.     android:versionName="1.0" >
  6.   
  7.     <uses-sdk
  8.         android:minSdkVersion="8"
  9.         android:targetSdkVersion="16" />
  10.   
  11.     <application
  12.         android:allowBackup="true"
  13.         android:icon="@drawable/ic_launcher"
  14.         android:label="@string/app_name"
  15.         android:theme="@style/AppTheme" >
  16.         <activity
  17.             android:name="com.marschen.s01e26_service01.MainActivity"
  18.             android:label="@string/app_name" >
  19.             <intent-filter>
  20.                 <action android:name="android.intent.action.MAIN" />
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />
  23.             </intent-filter>
  24.         </activity>
  25.           
  26.         <service android:name="com.marschen.s01e26_service01.SecondService">   //注册服务。
  27.               
  28.         </service>
  29.     </application>
  30.   
  31. </manifest>

4、布局:

点击(此处)折叠或打开

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     xmlns:tools="http://schemas.android.com/tools"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     tools:context=".MainActivity" >

  6.     <Button
  7.         android:id="@+id/button"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content"
  10.         android:layout_centerHorizontal="true"
  11.         android:layout_centerVertical="true"
  12.         android:text="完成绑定操作" />

  13. </RelativeLayout>


5、新建一个MainActivity.java 。该类其实是新建了一个Button,给该Button添加了一个监听器。要实现Activity和Service中间的通信,必须使用bindService方法,而其中需要三个参数intent(新建Intent对象,其中Intent对象连接MainActivity.this和SecondService.class,把该intent传进去即可),第二个参数ServiceConnection对象(新建一个ServiceConnection内部类,需要重写两个方法,其中在onServiceConnected方法中创建在SecondService(要绑定的Service)中的Binder对象FirstBinder,调用其中的getData方法,得到返回的数据,最后打印出来,这样其实已经完成了Activity和Service的绑定大半工作),最后一个参数flags(这里直接用BIND_AUTO_CREATE即可),最后就完成了Activity和Service的绑定。效果是在对Button进行点击,就能从Service的数据传到Activity中,在控制台打印出在Service中传过来的数据。

点击(此处)折叠或打开

  1. package com.marschen.s01e26_service01;

  2. import com.marschen.s01e26_service01.SecondService.FirstBinder;

  3. import android.os.Bundle;
  4. import android.os.IBinder;
  5. import android.app.Activity;
  6. import android.content.ComponentName;
  7. import android.content.Intent;
  8. import android.content.ServiceConnection;
  9. import android.view.Menu;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;

  13. public class MainActivity extends Activity {

  14.     Button button=null;
  15.     @Override
  16.     protected void onCreate(Bundle savedInstanceState) {
  17.         super.onCreate(savedInstanceState);
  18.         setContentView(R.layout.activity_main);
  19.     
  20.         button=(Button)findViewById(R.id.button);
  21.         button.setOnClickListener(new OnClickListener() {
  22.             
  23.             @Override
  24.             public void onClick(View v) {
  25.                 
  26.                 // TODO Auto-generated method stub
  27.                 Intent intent=new Intent();
  28.                 intent.setClass(MainActivity.this, SecondService.class);
  29.                 
  30.                 bindService(intent, conn, BIND_AUTO_CREATE);  //绑定服务。
  31.             }
  32.         });
  33.     }
  34.     
  35.     ServiceConnection conn = new ServiceConnection() {
  36.         
  37.         @Override
  38.         public void onServiceDisconnected(ComponentName name) {
  39.             // TODO Auto-generated method stub
  40.             
  41.         }
  42.         
  43.         @Override
  44.         public void onServiceConnected(ComponentName name, IBinder service) {
  45.             // TODO Auto-generated method stub
  46.             FirstBinder binder = (FirstBinder) service;
  47.             String data = binder.getData();
  48.             System.out.println("data----->"+ data);
  49.         }
  50.     };

  51.     @Override
  52.     public boolean onCreateOptionsMenu(Menu menu) {
  53.         // Inflate the menu; this adds items to the action bar if it is present.
  54.         getMenuInflater().inflate(R.menu.activity_main, menu);
  55.         return true;
  56.     }

  57. }

6、新建一个SecondService.java 的类,该类继承Service。onBind方法是继承Service方法必须复写的方法。新建一个内部类FirstBinder继承于Binder,当中的getData方法返回一个字符串。在onBind方法中新建一个IBinder对象,利用向下转型新建一个FirstBinder对象,然后返回这个IBinder对象。

点击(此处)折叠或打开

  1. package com.marschen.s01e26_service01;

  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;

  6. public class SecondService extends Service{

  7.     
  8.     //其他应用程序组件(Activity)绑定至当前的Service对象时,会调用该方法
  9.     @Override
  10.     public IBinder onBind(Intent intent) {
  11.         // TODO Auto-generated method stub
  12.         IBinder binder = new FirstBinder();
  13.         return binder;
  14.     }
  15.     
  16.     class FirstBinder extends Binder{
  17.         public String getData() {
  18.             return "test data";
  19.         }
  20.     }

  21. }

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(4) | 评论(0) | 转发(0) |
0

上一篇:Android TCP 和 UDP

下一篇:service bunder 下 Parcel 用法

相关热门文章
  • Android之开发环境搭建
  • Android自定义View的实现...
  • AndroidManifest.xml配置文件...
  • Android源码调试方法详解...
  • 不用vs和cygwin!Eclipse+cdt...
  • 请问Linux默认shell的是什么 ...
  • 谁能够帮我解决LINUX 2.6 10...
  • 现在的博客积分不会更新了吗?...
  • shell怎么读取网页内容...
  • ssh等待连接的超时问题...
给主人留下些什么吧!~~
原创粉丝点击