码迷,mamicode.com
首页 > 其他好文 > 详细

Activity与Service交互(一)

时间:2016-05-12 17:15:10      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

方法一:

使用ASB模型

1.Activity启动Service
2.Service发送广播
3.在Activity上注册BroadcastReceiver接受广播


public class MainActivity extends Activity {
	TextView tv;
	MyReceiver receiver;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv=(TextView) findViewById(R.id.tv);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		receiver=new MyReceiver();
		IntentFilter filter=new IntentFilter();
		filter.addAction("ISAAC_MYSERVICE");//注册
		registerReceiver(receiver, filter);//注销
	}
	public void start(View v){
		Intent intent =new Intent(this,MyService.class);
		startService(intent);
	}
	public void stop(View v){
		Intent intent =new Intent(this,MyService.class);
		stopService(intent);
	}
	public class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action =intent.getAction();
			if("ISAAC_MYSERVICE".equals(action)){
				String time = intent.getStringExtra("time");
				tv.setText(time);
			}
		}
		
	}
}



public class MyService extends Service {
	/**
	 * onCreate()
	 * onStartCommand
	 * onDestroy()
	 */
	
	Handler h=new Handler();
	
	public MyService() {
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.i("boom","onCreate()");
		h.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//发送广播,把getServiceTime()发送出去
				Intent intent = new Intent("ISAAC_MYSERVICE");//别跟系统重名
				intent.putExtra("time", getServiceTime());
				sendBroadcast(intent);
				h.postDelayed(this, 1000);//每个1秒发一次
			}
		},1000);
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.i("boom","onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		h.removeCallbacksAndMessages(null);
		Log.i("boom","onDestroy()");
	}
	String getServiceTime(){
		SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:SS");
		return sdf.format(new Date());
	}
	@Override
	public IBinder onBind(Intent intent) {
		// TODO: Return the communication channel to the service.
		throw new UnsupportedOperationException("Not yet implemented");
	}
}



Activity与Service交互(一)

标签:

原文地址:http://blog.csdn.net/grindstone_fos/article/details/51360971

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!