`
ipFire
  • 浏览: 122062 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Android Service

阅读更多

Service的概念:

Service(服务)是在后台运行,与用户没有交互的组件.Android支持二种服务:本地服务和远程服务.本地服务无法供在设备上运行的其他应用程序访问,远程服务则可以供其它程序访问.

 

Service的生命周期:

Service的生命周期只有onCreate,onStart,onDestroy,.

1)通过startService启动:开始(onCreate -> onStart)过程,Service停止的时候直接进入销毁过程(onDestory).如果调用者(Activity)自己退出而没用调用stopService(),刚service会一直运行下去,直到下次调用者(Activity)再启动起来,并确调用stopService();

2)通过bindService启动,只会运行onCreate,这时将调用者(Activity)与service绑定在一起,如果调用者(Activity)退出,service就会调用onUnbind -> onDestroy.

无论何种方式启动,service只会创建一起,即onCreate只会执行一次。

 

以下是一个简单的Demo

1.layout文件:

 

<?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:id="@+id/mText" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello" />

	<Button android:id="@+id/startService" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="startService" />
	<Button android:id="@+id/stopService" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="stopService" />
	<Button android:id="@+id/bindService" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="bindService" />
	<Button android:id="@+id/unbindService" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="unbindService" />
</LinearLayout>

 

 

2.创建service

 

package com.ex.service;

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 static final String TAG = "MyService";
	private int count = 0;

	// 这里定义一个Binder类,用在onBind()有方法里,这样Activity那边可以获取到
	private MyBinder mBinder = new MyBinder();

	public class MyBinder extends Binder {
		MyService getService() {
			return MyService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.e(TAG, "MyService --> onBind()");
		return mBinder;
	}

	@Override
	public void onCreate() {
		Log.e(TAG, "MyService --> onCreate()");
		super.onCreate();
		
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.e(TAG, "MyService --> onStart()");
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		Log.e(TAG, "MyService --> onDestroy()");
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.e(TAG, "MyService --> onUnbind()");
		return super.onUnbind(intent);
	}

	public int getCount(){
		return count;
	}
}

 

 

3.修改Activity

 

package com.ex.service;

import android.app.Activity;
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.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private static final String TAG = "MainActivity";
	private MyService myService = null;
	private TextView mText = null;
	
	//在Context.bindService和context.unBindService()里用到需要用到ServiceConnection
	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.i(TAG,"onServiceConnected");
			myService = ((MyService.MyBinder)service).getService();
			mText.setText("Service Time:"+myService.getCount());
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.i(TAG,"onServiceDisconnected");
		}
		
	};
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        mText = (TextView)findViewById(R.id.mText);
        //初始化按钮事件
        initButtons();
    }
	
	private void initButtons(){
		Button startService = (Button)findViewById(R.id.startService);
		startService.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				startService();
			}
		});
		
		Button stopService = (Button)findViewById(R.id.stopService);
		stopService.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				stopService();
			}
		});
		
		Button bindService = (Button)findViewById(R.id.bindService);
		bindService.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				bindService();
			}
		});
		
		Button unbindService = (Button)findViewById(R.id.unbindService);
		unbindService.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				unbindService();
			}
		});
	}
	//开启服务
	private void startService(){
		Intent intent = new Intent(MainActivity.this,MyService.class);
		this.startService(intent);
	}
	//关闭服务
	private void stopService(){
		Intent intent = new Intent(MainActivity.this,MyService.class);
		this.stopService(intent);
	}
	//绑定服务
	private void bindService(){
		Intent intent = new Intent(MainActivity.this,MyService.class);
		this.bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
	}
	//切断服务
	private void unbindService(){
		this.unbindService(mServiceConnection);
	}
}

 

 

4.修改AndroidManifest.xml(注册service)

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ex.service"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".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" android:exported="true"></service>  
    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest> 
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics