Android Service与Activity交互

andriod程序中,service一般处于后台运行,activity则有相应的界面,能与用户交互。本例主要研究service与activity之间通信,实现机制是service发送一个广播,activity注册接收器,在接收到相应的广播后执行相应的动作。先看效果图:

Android Service与Activity交互_第1张图片

首先点击按钮后service启动,service中有个线程在第五秒的时候向系统发送广播,activity获取到广播后关闭service,并将service传过来的值显示出来。通过广播信息实现service与activity的信息交互。 具体代码如下,重要代码已给出注释:

MainActivity实现广播接收器,并过滤广播信息,针对service的广播作出回应,具体代码:

package com.example.servicedemo;

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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private mServiceReceiver mReceiver;
	private TextView mTextView;
	private Button mButton01, mButton02;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTextView = (TextView) findViewById(R.id.txt);
		mButton01 = (Button) findViewById(R.id.btn01);
		mButton02 = (Button) findViewById(R.id.btn02);
		//启动service服务
		mButton01.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainActivity.this,mService1.class);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startService(i);
				Toast.makeText(MainActivity.this, "服务启动", Toast.LENGTH_SHORT).show();
				mTextView.setText("服务启动");
			}
		});
		
		//终止服务
		mButton02.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(MainActivity.this,mService1.class);
				if(stopService(i) == true){
					mTextView.setText("服务关闭");
					Toast.makeText(MainActivity.this, "服务已经关闭", Toast.LENGTH_SHORT).show();
				}else{
					mTextView.setText("服务关闭出错");
				}
			}
		});
	}
	
	@Override
	protected void onResume(){
		try{
			//前端程序生命周期开始
			IntentFilter mFilter;
			//自定义要过滤的广播信息
			mFilter = new IntentFilter(mService1.HIPPO_SERVICE_IDENTIFIER);
			mReceiver = new mServiceReceiver();
			registerReceiver(mReceiver,mFilter);
		}catch(Exception e){
			mTextView.setText(e.toString());
			e.printStackTrace();
		}
		super.onResume();
	}
	
	@Override
	protected void onPause(){
		//前端程序生命周期结束,解除向系统注册的receiver
		unregisterReceiver(mReceiver);
		super.onPause();
	}
	
	public class mServiceReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			try{
				//获取来自后台服务Broadcast的参数
				Bundle bundle = intent.getExtras();
				String strParaml = bundle.getString("STR_PARAM1");
				//将从service里传来的广播信息显示在textview上
				mTextView.setText(strParaml);
				Intent i = new Intent(MainActivity.this,mService1.class);
				//若关闭service则弹出框提示用户
				if(stopService(i) == true){
					Toast.makeText(MainActivity.this, "服务已经关闭", Toast.LENGTH_SHORT).show();
				}
			}catch(Exception e){
				mTextView.setText(e.toString());
				e.printStackTrace();
			}
		}
		
	}

}

mService1继承Service,并实现广播发送代码:

package com.example.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class mService1 extends Service{
	
	//创建handler对象
	private Handler objHandler = new Handler();
	
	//服务里面的递增整数counter
	private int intCounter = 0;
	
	//自定义要过滤的广播信息
	public static final String HIPPO_SERVICE_IDENTIFIER = "DavidLanz";
	
	//进程每秒运行一次
	private Runnable mTasks = new Runnable(){
		public void run(){
			intCounter ++;
			
			//当后台service运行5秒之后,送出自定义的广播信息
			if(intCounter == 5){
				//DavidLanz
				Intent i = new Intent(HIPPO_SERVICE_IDENTIFIER);
				//通过putExtra方法封装参数返回Activity
				i.putExtra("STR_PARAM1", "信息来自service,将为您关闭service");
				sendBroadcast(i);
			}
			objHandler.postDelayed(mTasks, 1000);
		}
	};
	
	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent,int startId){
		super.onStart(intent, startId);
	}
	
	@Override
	public void onCreate(){
		//服务开启,启用进程
		objHandler.postDelayed(mTasks, 1000);
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onDestroy(){
		// 关闭服务关闭进程 
		objHandler.removeCallbacks(mTasks);
		super.onDestroy();
	}

}
AndroidManifest.xml配置:




    

    
        
            
                

                
            
        
        
    



demo下载



你可能感兴趣的:(android)