[转帖]Android中的Service使用_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2823 | 回复: 0   主题: [转帖]Android中的Service使用        下一篇 
shuangqiang.xing
注册用户
等级:上尉
经验:737
发帖:64
精华:0
注册:2013-10-30
状态:离线
发送短消息息给shuangqiang.xing 加好友    发送短消息息给shuangqiang.xing 发消息
发表于: IP:您无权察看 2013-11-4 9:21:28 | [全部帖] [楼主帖] 楼主

Service的生命周期 (适用于2.1及以上)

1. 被startService的
无论是否有任何活动绑定到该Service,都在后台运行。onCreate(若需要) -> onStart(int id, Bundle args).  多次startService,则onStart调用多次,但不会创建多个Service实例,只需要一次stop。该Service一直后台运行,直到stopService或者自己的stopSelf()或者资源不足由平台结束。

2. 被bindService的
调用bindService绑定,连接建立服务一直运行。未被startService只是BindService,则onCreate()执行,onStart(int,Bundle)不被调用;这种情况下绑定被解除,平台就可以清除该Service(连接销毁后,会导致解除,解除后就会销毁)。

3. 被启动又被绑定
类似startService的生命周期,onCreate onStart都会调用。

4. 停止服务时
stopService时显式onDestroy()。或不再有绑定(没有启动时)时隐式调用。有bind情况下stopService()不起作用。

以下是一个简单的实现例子,某些部分需要配合logcat观察。

AcMain.java

  1. package jtapp.myservicesamples;
  2. import android.app.Activity;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.ServiceConnection;
  7. import android.os.Bundle;
  8. import android.os.IBinder;
  9. import android.util.Log;
  10. import android.view.View;
  11. import android.view.View.OnClickListener;
  12. import android.widget.Button;
  13. import android.widget.Toast;
  14. public class AcMain extends Activity implements OnClickListener {
  15.        private static final String TAG = "AcMain";
  16.        private Button btnStart;
  17.        private Button btnStop;
  18.        private Button btnBind;
  19.        private Button btnExit;
  20.        
  21.        /** Called when the activity is first created. */
  22.        @Override
  23.        public void onCreate(Bundle savedInstanceState) {
  24.              super.onCreate(savedInstanceState);
  25.              setContentView(R.layout.main);
  26.              
  27.              findView();
  28.        }
  29.       
  30.        private void findView() {
  31.              btnStart = (Button) findViewById(R.id.Start);
  32.              btnStop = (Button) findViewById(R.id.Stop);
  33.              btnBind = (Button) findViewById(R.id.Bind);
  34.              btnExit = (Button) findViewById(R.id.Exit);
  35.              
  36.              btnStart.setOnClickListener(this);
  37.              btnStop.setOnClickListener(this);
  38.              btnBind.setOnClickListener(this);
  39.              btnExit.setOnClickListener(this);
  40.        }
  41.       
  42.        @Override
  43.        public void onClick(View v) {
  44.              Intent intent = new Intent("jtapp.myservicesamples.myservice");
  45.              switch(v.getId()) {
  46.                    case R.id.Start:
  47.                    startService(intent);
  48.                    Toast.makeText(this, 
  49.                    "myservice running " + MyService.msec/1000.0 + "s.", 
  50.                    Toast.LENGTH_LONG).show();
  51.                    break;
  52.                    case R.id.Stop:
  53.                    stopService(intent);
  54.                    Toast.makeText(this,
  55.                    "myservice running " + MyService.msec/1000.0 + "s.", 
  56.                    Toast.LENGTH_LONG).show();
  57.                    break;
  58.                    case R.id.Bind:
  59.                    bindService(intent, sc, Context.BIND_AUTO_CREATE);
  60.                    break;
  61.                    case R.id.Exit:
  62.                    this.finish();
  63.                    break;
  64.              }
  65.        }
  66.        
  67.        private MyService serviceBinder;
  68.        
  69.        private ServiceConnection sc = new ServiceConnection() {
  70.              @Override
  71.              public void onServiceDisconnected(ComponentName name) {
  72.                    Log.d(TAG, "in onServiceDisconnected");
  73.                    serviceBinder = null;
  74.              }
  75.              @Override
  76.              public void onServiceConnected(ComponentName name, IBinder service) {
  77.                    Log.d(TAG, "in onServiceConnected");
  78.                    serviceBinder = ((MyService.MyBinder)service).getService();
  79.              }
  80.        };
  81.       
  82.        @Override
  83.        protected void onDestroy() {
  84.              //this.unbindService(sc);
  85.              //this.stopService(
  86.              // new Intent("jtapp.myservicesamples.myservice"));
  87.              super.onDestroy();
  88.        }
  89. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <TextView android:layout_width="fill_parent"
  6.                 android:layout_height="wrap_content" android:text="@string/hello" />
  7.         <Button android:text="Start MyService" android:id="@+id/Start"
  8.                 android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  9.         <Button android:text="Stop MyService" android:id="@+id/Stop"
  10.                 android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  11.         <Button android:text="Bind MyService" android:id="@+id/Bind"
  12.                 android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  13.         <Button android:text="Exit AcMain" android:id="@+id/Exit"
  14.                 android:layout_width="wrap_content" android:layout_height="wrap_content"/>
  15. </LinearLayout>

MyService.java

  1. package jtapp.myservicesamples;
  2. import android.app.Service;
  3. import android.content.Intent;
  4. import android.os.Binder;
  5. import android.os.IBinder;
  6. import android.util.Log;
  7. public class MyService extends Service {
  8.        private static final String TAG = "MyService";
  9.        public static long msec = 0;
  10.        private boolean bThreadRunning = true;
  11.        
  12.        
  13.        private final IBinder binder = new MyBinder();
  14.        public class MyBinder extends Binder {
  15.              MyService getService() {
  16.                    return MyService.this;
  17.              }
  18.        }
  19.        @Override
  20.        public IBinder onBind(Intent intent) {
  21.              return binder;
  22.        }
  23.       
  24.        @Override
  25.        public void onCreate() {
  26.              new Thread(new Runnable(){
  27.                    @Override
  28.                    public void run() {
  29.                          while (bThreadRunning) {
  30.                                try {
  31.                                      Thread.sleep(100);
  32.                                } catch (InterruptedException e) {
  33.                                }
  34.                                Log.i(TAG, "myservice running " + (msec+=100) + "ms.");
  35.                          }
  36.                    }
  37.              }).start();
  38.        }
  39.       
  40.        @Override
  41.        public void onDestroy() {
  42.              bThreadRunning = false;
  43.              super.onDestroy(); // 可以不用
  44.        }
  45.       
  46. }


复制代码

AnndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3.         package="jtapp.myservicesamples" android:versionCode="1"
  4.         android:versionName="1.0">
  5.         <application android:icon="@drawable/icon" android:label="@string/app_name"
  6.                 android:debuggable="true">
  7.                 <activity android:name=".AcMain" android:label="@string/app_name">
  8.                         <intent-filter>
  9.                                 <action android:name="android.intent.action.MAIN" />
  10.                                 <category android:name="android.intent.category.LAUNCHER" />
  11.                         </intent-filter>
  12.                 </activity>
  13.                 <service android:name="MyService">
  14.                         <intent-filter>
  15.                                 <action android:name="jtapp.myservicesamples.myservice"></action>
  16.                         </intent-filter>
  17.                 </service>
  18.         </application>
  19. </manifest> 






赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论