android笔记:Service

服务:在后台运行,没有界面的组件。

服务生命周期如下:

两种启动方式:

1、startService(): onCreate()-->onStartCommand()-->onDestroy().
2、bindService():  onCreate()-->onBind()-->onUnbind()-->onDestroy().

一、定义一个服务,得做到以下:

1.继承Service,重写onBind()、onCreate()onStartCommand()onDestroy();

2.在AndroidManifest里面注册才能生效.

二、启动服务:

Intent startIntent=new Intent(this,MyService.class);

startService(startIntent);

三、停止服务:

Intent stopIntent=new Intent(this,MyService.class);
stopService(stopIntent);

四、绑定服务:

1.onBind()方法返回Binder对象;

2.创建了ServiceConnection 的匿名类,重写onServiceConnected()方法和 onServiceDisconnected()方法;

3.用bindService()方法将 Activity Service 进行绑定。

bindService()方法接收三个参数,第一个参数就Intent 对象,第二个参数是ServiceConnection 的实例,第三个
参数则是一个标志位,可以传入 BIND_AUTO_CREATE 表示在活动和服务进行绑定后自动创建服务。

示例如下:

Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);

五、解绑服务:

unbindService(connection);

六、使用IntentService

优点:

1.异步,可以在子线程处理耗时操作

2.执行完毕自动停止

 

代码示例如下:

MainActivity.java

 

package com.example.servicedemo;



import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
    private Button startService;
    private Button stopService;
    private Button bindService;
    private Button unbindService;
    private MyService.DownloadBinder downloadBinder;
    private Button startIntentService;
    private boolean mIsBound =false;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            downloadBinder=(MyService.DownloadBinder)service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService=(Button)findViewById(R.id.start);
        stopService=(Button)findViewById(R.id.stop);
        bindService = (Button) findViewById(R.id.bind_service);
        unbindService = (Button) findViewById(R.id.unbind_service);
        startIntentService = (Button) findViewById(R.id.start_intent_service);
        startIntentService.setOnClickListener(this);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
        bindService.setOnClickListener(this);
        unbindService.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()) {
          case R.id.start:
              Intent startIntent=new Intent(this,MyService.class);
              startService(startIntent);
              
             break;
          case R.id.stop:  
              Intent stopIntent=new Intent(this,MyService.class);
              stopService(stopIntent);
             break;
          case R.id.bind_service:   
              Intent bindIntent = new Intent(this, MyService.class);
              bindService(bindIntent,connection,BIND_AUTO_CREATE);//绑定服务
              mIsBound = true;
              break;
          case R.id.unbind_service:  
              if(mIsBound) {
                 unbindService(connection);  //解绑服务
                 Log.d("MainActivity","UnbindService");
                 mIsBound=false;
              }
            
              break;
          case R.id.start_intent_service:
                Log.d("MainActivity","Thread id is "+Thread.currentThread().getId());
                Intent intentService=new Intent(this,MyIntentService.class);
                startService(intentService);
                break;
          default:
              break;
        }
    }

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


 

 

 

 

 

MyService.java:

package com.example.servicedemo;

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{
    private DownloadBinder mBinder = new DownloadBinder();
    //继承Binder的内部类,一个方法开始下载,另一个方法获取进度
    class DownloadBinder extends Binder {
      public void startDownload() {
        Log.d("MyService", "startDownload executed");
      }
      public int getProgress() {
        Log.d("MyService", "getProgress executed");
        return 0;
    }
  }
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return mBinder;
    }

    public void onCreate(){
        super.onCreate();
        Log.d("MyService","onCreate executed");
    }
    
    public int onStartCommand(Intent intent,int flags,int startId){
        Log.d("MyService","onStartCommand executed");
        return super.onStartCommand(intent,flags,startId);
        
        
    }
    
    public void onDestroy(){
        Log.d("MyService","onDestroy executed");
        super.onDestroy();
    }
    
    
    
}

 

MyIntentService.java:

package com.example.servicedemo;

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class MyIntentService extends IntentService{

    public MyIntentService() {
        super("MyIntentService");
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        // TODO Auto-generated method stub
        Log.d("MyIntentService", "Thread id is " + Thread.currentThread().
                getId());
    }

    public void onDestroy() {
        super.onDestroy();
        Log.d("MyIntentService", "onDestroy executed");
        }
}

 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/start"
       android:text="start service"
       
       />

      <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/stop"
       android:text="stop service"       
       android:layout_below="@id/start"
       />
      
      <Button
         android:id="@+id/bind_service"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Bind Service" 
         android:layout_below="@id/stop"  />
      <Button
         android:id="@+id/unbind_service"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:text="Unbind Service" 
         android:layout_below="@id/bind_service" />
      
      <Button
       android:id="@+id/start_intent_service"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Start IntentService" 
       android:layout_below="@id/unbind_service"  />
       
</RelativeLayout>

 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.servicedemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.servicedemo.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>
        <service 
            android:name=".MyService"
            ></service>
       <service android:name=".MyIntentService"></service>
    </application>

</manifest>

 

运行效果如下所示:

 

start Service:

多次start Service:

Bind Service:

start IntentService:

 

posted on 2016-07-29 23:52  乐之者v  阅读(262)  评论(0编辑  收藏  举报

导航