四大组件之Service(一)

本文详细介绍了Android中的Service组件,包括如何实现活动与服务之间的通信、如何使用前台服务确保服务始终运行以及如何利用IntentService处理耗时任务并自动停止服务。

一知半解的人,多不谦虚;见多识广有本领的人,一定谦虚。   —— 谢觉哉


本讲内容:Service 服务组件
Service是Android程序中四大基础组件之一,它和Activity一样都是Context的子类,只不过它没有UI界面,是在后台运行的组件,优先级高于Activity。


一、活动和服务进行通信

在活动中可以启动服务,但活动并不知道服务到底去做了什么事情,譬如在活动中指挥服务去干什么,这就要借助onBind()方法来绑定服务了。当一个活动和服务绑定了之后,就可以调用该服务里的Binder(远程服务)提供的方法了。


示例一:


点击一下Start Service按钮

点击一下Stop Service按钮

点击一下Bind Service按钮

可以看到首先是MyService的onCreate()方法执行,然后是startDownload()和getProgress()方法都得到执行,说明我们已经在活动里成功调用了服务里提供的方法。

下面是res/layout/activity_main.xml 布局文件:

<LinearLayout 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:orientation="vertical" >

    <Button
        android:id="@+id/start_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Service" />

    <Button
        android:id="@+id/stop_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stop Service" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />

</LinearLayout>


下面是新建MyService.java文件:(要注册)

public class MyService extends Service{
	private static final String TAG="MainActivity";
	private DownloadBinder mBinder=new DownloadBinder();//创建DownloadBinder实例
	
	class DownloadBinder extends Binder{
		
		//开始下载
		public void startDownload(){
			Log.d(TAG, "startDownload executed");
		}
		
		//查看下载进度
		public int getProgress(){
			Log.d(TAG, "getProgress executed");
			return 0;
		}
	}

	//Service中唯一的一个抽象方法,即当调用bindService()方法后被调用,调用该方法可以获取返回的IBinder对象的实例
	public IBinder onBind(Intent intent) {
		return mBinder;//返回mBinder这个实例
	}
	
	//服务创建的时候调用
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate executed");
	}
	
	//每次服务启动的时候调用
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(TAG,"onStartCommand executed");
		return super.onStartCommand(intent, flags, startId);
	}
	
	//在服务销毁的时候调用
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy executed");
	}

}


下面是MainActivity.java主界面文件:

public class MainActivity extends Activity implements OnClickListener{
	private Button startService;
	private Button stopService;
	private Button bindService;
	private Button unbindService;
	private MyService.DownloadBinder downloadBinder;
	
	private ServiceConnection connection=new ServiceConnection() {
		
		//活动与服务解除绑定的时候调用
		public void onServiceDisconnected(ComponentName name) {
		}
		
		//活动与服务成功绑定的时候调用
		public void onServiceConnected(ComponentName name, IBinder service) {
			//得到DownloadBinder的实例,就可以指挥服务干什么了。
			downloadBinder=(DownloadBinder) service;
			downloadBinder.startDownload();
			downloadBinder.getProgress();
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		startService=(Button) findViewById(R.id.start_service);
		stopService=(Button) findViewById(R.id.stop_service);
		bindService=(Button) findViewById(R.id.bind_service);
		unbindService=(Button) findViewById(R.id.unbind_service);
		
		startService.setOnClickListener(this);
		stopService.setOnClickListener(this);
		bindService.setOnClickListener(this);
		unbindService.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_service:
			Intent startIntent=new Intent(this,MyService.class);
			startService(startIntent);
			break;
		case R.id.stop_service:
			Intent stopIntent=new Intent(this,MyService.class);
			stopService(stopIntent);
			break;
		case R.id.bind_service:
			Intent bindIntent=new Intent(this,MyService.class);
			//第二个参数是前面创建出的ServiceConnection实例,第三个参数是一个标志位,这里传入BIND_AUTO_CREATE表示
			//在活动和服务进行绑定后自动创建服务,即使得MyService中的onCreate()方法执行,但onStartCommand()方法不会执行
			bindService(bindIntent,connection,BIND_AUTO_CREATE);//绑定服务
			break;
		case R.id.unbind_service:
			unbindService(connection);
			break;
		default:
			break;
		}
	}
}


二、使用前台服务

服务几乎都是在后台运行的,服务的系统优先级还是比较低的,当系统出现内存不足时,就有可以会回收掉正在后台运行的服务。如果你希望服务可以一起保持运行状态,可以使用前台服务。前台服务和后台服务最大区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,譬如墨迹天气。


示例二:前台服务

  

点击Start Service或Bind Service按钮,MyService就会以前台服务的模式启动了

修改MyService中的代码

//服务创建的时候调用
public void onCreate() {
		super.onCreate();
		Notification notification=new Notification(R.drawable.ic_launcher,"Notification comes",System.currentTimeMillis());
		Intent notificationIntent=new Intent(this,MainActivity.class);
		PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(this, "This is title", "This is content", pendingIntent);
		//调用startForeground()方法后就会让MyService变成前台服务,并在系统状态栏显示出来,第一个参数是通知的ID,类似于notify()方法的第一个参数
		startForeground(1, notification);
		
		Log.d(TAG, "onCreate executed");
	}


三、使用IntentService类

服务中的代码都是默认运行在主线程当中的,如果直接在服务里去处理一些耗时的逻辑,就很容易出现ANR错误。所以我们应该在服务的每个具体方法里开启一个子线程。然后在这里去处理那些耗时的逻辑。为了可以简单地创建一个异步,并且会自动停止的服务,Android专门提供了一个IntentService类。


示例三:使用IntentService服务


点击按钮


可以看到,不仅MyIntentService和MainActivity所在的线程id不同,而且onDestroy()方法也得到执行,说明MyIntentService在运行完毕后会自动停止服务的。

下面是res/layout/activity_main.xml 布局文件:

<LinearLayout 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" >

    <Button
        android:id="@+id/start_intent_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start IntentService" />

</LinearLayout>

下面是新建MyIntentService.java文件:

public class MyIntentService extends IntentService{
	private static final String TAG="MainActivity";

	public MyIntentService() {
		super("MyIntentService");//调用父类的有参构造函数
	}

	//这个方法是在子线程中运行的,可以用于处理一些具体的逻辑
	protected void onHandleIntent(Intent intent) {
		//打印当前线程的ID
		Log.d(TAG, "MainThread id is "+Thread.currentThread());
	}
	
	public void onDestroy() {
		super.onDestroy();
		Log.d(TAG, "onDestroy executeed");
	}

}
注册

<service android:name=".MyIntentService"></service>

下面是MainActivity.java主界面文件:

public class MainActivity extends Activity implements OnClickListener{
	private static final String TAG="MainActivity";
	private Button startIntentService;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		startIntentService=(Button) findViewById(R.id.start_intent_service);
		startIntentService.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_intent_service:
			//打印主线程的ID
			Log.d(TAG, "Thread id is "+Thread.currentThread());
			Intent intentService=new Intent(this,MyIntentService.class);
			startService(intentService);
			break;
		default:
			break;
		}
	}
}



Take your time and enjoy it

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值