服务与活动之间通信

作者:追风剑情 发布于:2015-8-1 21:24 分类:Android

服务使用BroadcastReceiver来与活动通信。

活动

package com.example.androidtest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class ServicesActivity extends Activity {

	IntentFilter intentFilter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_services);
	}
	
	public void startService(View view){
		startService(new Intent(getBaseContext(), MyIntentService.class));
	}
	
	public void stopService(View view){
		stopService(new Intent(getBaseContext(), MyIntentService.class));
	}
	
	@Override
	public void onResume(){
		super.onResume();
		
		intentFilter = new IntentFilter();
		intentFilter.addAction("FILE_DOWNLOADED_ACTION");
		//注册意图侦听
		registerReceiver(intentReceiver, intentFilter);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		//注销意图侦听
		unregisterReceiver(intentReceiver);
	}
	
	//处理侦听到的意图广播
	private BroadcastReceiver intentReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Toast.makeText(getBaseContext(), "File downloaded!", Toast.LENGTH_LONG).show();
		}
		
	};
}

服务

package com.example.androidtest;

import java.net.MalformedURLException;
import java.net.URL;

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

/**
 * 继承IntentService的服务,在任务执行完成后会自行终止。
 * 无需手动调用stopSelf()、stopService()
 * 
 * @author Administrator
 *
 */
public class MyIntentService extends IntentService {

	public MyIntentService() {
		//必需实现这个类的构造函数
		super("MyIntentServiceName");
	}

	// 此方法在工作者线程上执行
	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			int result = DownLoadFile(new URL("http://www.amazon.com/somefile.pdf"));
			Log.d("AndroidTest", "Downloaded " + result + " bytes");
			
			//广播一个意图
			Intent broadcastIntent = new Intent();
			broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
			getBaseContext().sendBroadcast(broadcastIntent);
			
		} catch (MalformedURLException e) {
			Log.d("AndroidTest", e.getMessage());
		}
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		Toast.makeText(this, "MyIntentService Destroyed", Toast.LENGTH_LONG).show();
	}

	private int DownLoadFile(URL url)
	{
		try{
			Thread.sleep(5000);//模拟文件下载
		}catch(InterruptedException e){
			Log.d("AndroidTest", e.getMessage());
		}
		return 100;//文件大小
	}
}

运行效果

11111111111.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号