Android学习--Service1

本文详细介绍了Android中服务的生命周期、创建方法及其特点。包括服务的启动、绑定、停止和解绑流程,以及如何在服务中开启子线程进行耗时操作。同时,文章还对比了直接在Activity中开启子线程与使用Service的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

0.生命周期

onCreate(第一次创建)--onStart()--onDestory()

1.创建方法1

--Intent intent=new Intent(this,MySerivce.class)

--startService(intent)

--stopService(intent)

活动结束,服务不一定结束

2.创建方法2,随着绑定的Activity销毁

-- connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
my=(MyService.MyBinder)arg1;//获取MyService中的Binder类型对象,调用它的public方法,Service需要实现onBind,返回Service中的Binder类型对象
my.dosome();
}
};

--Intent in2=new Intent(this,MyService.class);

-- bindService(in2,connection,BIND_AUTO_CREATE);

--unbindService(connection)

3.Service特点能够跨应用程序调用。

调用Service服务的程序称为Client,如果Service和Client在同一应用程序中,默认在同一进程同一线程运行,因此为了不使Client挂起,可在Service重建一个Thread完成耗时操作。

如果Client在另一个程序中,两者运行在不同进程中,不同Client获取相同的MyBinder实例。

Service运行在主线程里

4.标准的Service中开启子线程进行耗时操作,有一个类IntentService中的方法默认在子线程中运行的  

和直接在Activity开启子线程相比,后者Activity对Thread难以控制,销毁后无法获取之前子线程的实例。使用Service则可以重建建立连接,获取MyBinder实例。

并且一个Activity的子线程另一个Activity是无法访问的。

5.常见模式startService(启动)--bindService(建立连接)--stopService(停止)--unBindService(解绑)--销毁

Tips:Service需要注册,和Activity一样。

<service android:name="XXXX" ></service>//注意格式

MainActivity

package com.example.servicetest;

import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener{
	private Button btn1;
	private Button btn2;
	private Button btn3;
	private Button btn4;
	private MyService.MyBinder my;
	private ServiceConnection connection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       connection=new ServiceConnection() {
			
			@Override
			public void onServiceDisconnected(ComponentName arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onServiceConnected(ComponentName arg0, IBinder arg1) {
				// TODO Auto-generated method stub
				my=(MyService.MyBinder)arg1;
				my.dosome();
			}
		};
        btn1=(Button)findViewById(R.id.button1);
        btn2=(Button)findViewById(R.id.button2);
        btn3=(Button)findViewById(R.id.button3);
        btn4=(Button)findViewById(R.id.button4);
        
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener( this);
        btn4.setOnClickListener( this);
           }

    
    public void onClick(View view)
    {
    	switch(view.getId())
    	{
    	case R.id.button1:
    		Intent in=new Intent(this,MyService.class);
    		System.out.print("start");
    		//Log.i("start","start");
    		startService(in);
    		break;
    		
    	case R.id.button2:
    		Intent st=new Intent(this,MyService.class);
    		System.out.print("stop");
    		stopService(st);
    		break;
    	case R.id.button3:
    		Intent in2=new Intent(this,MyService.class);
    		//startService(in);
    		bindService(in2,connection,BIND_AUTO_CREATE);
    		System.out.print("bind");
    		break;
    	case R.id.button4:
    		//Intent in2=new Intent(this,MyService.class);
    		//startService(in);
    		unbindService(connection);
    		System.out.print("unbind");
    		break;
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
   
    
}

MyService

package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {

	public static int  count=0;
	private MyBinder myBinder=new MyBinder();
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}
	class MyBinder extends Binder
	{
		public void dosome()
		{
			Log.i("count", count+"");
			count++;
		}
	}
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return myBinder;
	}

}

IntentService

1.继承Intentservice并提供一个无参数的构造函数,在方法内部调用父类的构造函数。
2.重写父类当中onhandleintent这个方法,把我们要在服务当中处理的逻辑过程都放在这个方法内完成
3.启动这个service。 这个服务的特殊之处就在于onhandleintent这个方法,这个方法内部的代码都是在子线程中运行的,并且在这个方法执行到末尾的时候,会自动的帮我们关闭service。

其余启动方法和普通service类似的

package com.example.servicetest;

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

public class MyIntentService extends IntentService {

	public MyIntentService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	//必须提供一个默认构造函数
	public MyIntentService() {
		super("my service");
		// TODO Auto-generated constructor stub
	}
	

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("xuran1", "服务关闭 ");
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		// TODO Auto-generated method stub
		for(int i = 0; i < 10; i++){
			 
	        System.out.println(i);
	        try {
	            Thread.sleep(1000);
	        } catch (InterruptedException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	    }
	}

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值