欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

android开发 关于Service的研究

来源: 开发者 投稿于  被查看 12345 次 评论:85

android开发 关于Service的研究


两年学习android开发的时候 了解到Service的技术

一直没抽出时间整理这块内容 现在终于有时间来详细的比较深入的编码 理解这个Service了


一. Service与Activity

android开发是离不开Activity的 Activity相当于WIN的窗口

但是一般只有一个现实在前端 其他的Activity要么压到后台的栈中 要么手动销毁掉了

而Service是可以启动多个的 这样多个Service就是相当是并行状态

并且 这个Service可以和Activity保持相对独立

换句话说 可以ActivityA中启动Service

在ActivityB中给Service发消息

最后在ActivityC中关闭Service

这几个Activity轮流现实在前端


二. Service与线程

其实 理解线程的话 就很容易理解Service

Activity Service 都是在主线程中执行的 不过Activity对象是只有一个显示在前端

而Service 不显示在前端 并可以生成多个对象

这样存储在Service的数据 不会像Activity内的数据 随着Activity销毁而销毁

另外可以开启新的线程 作为后台处理线程

完全独立于Activity 只处理Activity发来的消息


三. Code


manifest中

注册2个activity 一个Service

            
                

                
            
        
        
          
          
        
		
布局

activity_main 第一个activity 给三个按钮 开始Service 结束Service 和下一个界面

activity_sec 第二个activity 也给三个按钮 退出界面 发送消息2和结束Service


MainActivity的按钮处理

	public void onClick(View arg0) {
		// TODO Auto-generated method stub
        switch (arg0.getId()) {
        case (R.id.button_on):
        	//启动 Service
        	this.startService(new Intent(this, PlayService.class));
            break;
        case (R.id.button_off): {
        	//停止 Service
             this.stopService(new Intent(this,PlayService.class));
        }
            break;
        case (R.id.button_next): {
        	//打开另一个Activity
        	Intent intent = new Intent();
    		intent.setClass(MainActivity.this, SecActivity.class);
    		startActivity(intent);
        
        }
            break;
         default:
             break;
        
        }
	}


SecActivity的按钮处理

	public void onClick(View arg0) {

        switch (arg0.getId()) {
        case (R.id.button_esc):
        	//退出Activity
        	finish();
            break;
        case (R.id.button_off): {
        	//关闭Service
        	this.stopService(new Intent(this,PlayService.class));
        }
            break;
        case (R.id.button_step2): {
        	//向Service	发消息
        	Intent intent = new Intent(this, PlayService.class);
        	Bundle bundle = new Bundle();  
        	bundle.putInt("op", 2);  
        	intent.putExtras(bundle);  

            this.startService(intent);
       }
        break;
        default:
        	break;
        }
	}


PlayService完整代码

public class PlayService extends Service {

	private HandlerThread mHandlerThread;
	private Handler mPlayHandler;
    
    class PlayHandler extends Handler{
    	public PlayHandler(){
    		
    	}
    	
    	public PlayHandler(Looper lp){
    		super(lp);
    	} 
    	
    	@Override
    	public void handleMessage(Message msg) {
    		// TODO Auto-generated method stub
    		super.handleMessage(msg);
    		
    		//接收到线程处理的数据
    		// 注意 这里已经不是主线程上 而是独立的线程上 
    		System.out.println("PlayHandler handleMessage");
    		System.out.println("PlayHandler thread id :"+Thread.currentThread().getId());
    	}
    }

	@Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
    	System.out.println("PlayService on onBind");
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "Play Service Created", Toast.LENGTH_SHORT).show();
        System.out.println("PlayService on onCreate");
        
        //启动线程
        mHandlerThread	= new HandlerThread("Play_Service_thread");
        mHandlerThread.start();
        mPlayHandler	= new PlayHandler(mHandlerThread.getLooper());
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        
      //onStart 可以用于接收Activity发来的消息
       //注意 到这里还是处于主线程上
        Toast.makeText(this, "Play Service onStart", Toast.LENGTH_SHORT).show();

        System.out.println("PlayService on onStart");
        System.out.println("PlayService thread id :"+Thread.currentThread().getId());
        
        if (intent != null) {  
    		Bundle bundle = intent.getExtras();  
    		if (bundle != null) {  
    		int op = bundle.getInt("op");  
    		switch (op) {  
  
    		case 2:  
    			//通过Message对象 转发给线程处理
    			System.out.println("PlayService on onStart  step2");
    			Message msg = mPlayHandler.obtainMessage();
    			msg.sendToTarget();
    		break;  

    			}  
    		}  
    	}//if
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "Play Service Stopped", Toast.LENGTH_SHORT).show();

        System.out.println("PlayService on Destroy");
        
        //退出线程 销毁数据
        mHandlerThread.quit();
        mHandlerThread = null;
        mPlayHandler = null;
    }
}


Service的生成与销毁都可以在Activity内调用

但是Service的生命周期不等于Activity 而是在主线程 这是得注意的地方




用户评论