android-service

Service
    启动需要 两种方法(面试的时候会问到)
startService():
context.startService()  -> onCreate()  -> onStart()  -> Service running  -> context.stopService()  -> onDestroy()  -> Service stop
值得注意的是:服务一旦开启,无论在开启多少次都不会在运行oncreate方法,同样的  也不会再运行onStop方法
BindService():
context.bindService()  -> onCreate()  -> onBind()  -> Service running  -> onUnbind()  -> onDestroy()  -> Service stop

区别:
startService     是启动之后与启动者没有什么联系(启动的activity),启动者无法对service进行操作
bindService   是和service绑定在一起的,启动者停止,服务也停止。
startService案例代码:
public class Texts_Service extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		System.out.println("onCreate()-----------");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}

首先是 继承Service 会自动重写onBind方法。但是不要忘了在Manifest里面注册
<service android:name="com.startservice.Texts_Service" >
        </service>

service和activity是同级的同样都在application目录下
public class TextS_Ser extends Activity{
	private Button btn_Start;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.texts_ser);
		btn_Start =(Button) findViewById(R.id.Start);
		btn_Start.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startService(new Intent(TextS_Ser.this,Texts_Service.class));
			}
		});
	}

}

在开发过程中,不可能只是实现这么个简单的功能,外界操作一个服务如何实现。

与上边一些样,实现service,按钮实现启动与停止
package com.handlers;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

	private boolean running = false;
	private String data;

	public MyService() {
		super();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	/**
	 * 当执行完 oncreate方法之后就会执行onStart方法 之后 执行onStartCommand方法(Service生命周期)
	 * 外界传递的参数就会在这里获取
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		data = intent.getStringExtra("data");
		return super.onStartCommand(intent, flags, startId);
		
	}
/**
 * 对于service的操作就在这块实现
 * 这里使用的是线程,每个一秒发送一次
 */

	@Override
	public void onCreate() {
		super.onCreate();
		running = true;
		new Thread() {
			@Override
			public void run() {
				super.run();
				while (running) {
					// Toast.makeText(getApplication(), "默认信息", 0).show();
					System.out.println(data+"-------------------");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}.start();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		running = false;
	}
}

在MainActivity中设置点击事件,并传递参数
package com.handlers;

import com.example.text_scort_android.R;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText edText;
	private Button start,stop;
	public Handler handler  ;
	private MyBinder binder = new MyBinder();
	
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
			Toast.makeText(getApplicationContext(), "UnConnection", 0).show();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			binder = (MyBinder) service;
			binder.Middle(getApplication());
		}
	};
	 

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edText = (EditText) findViewById(R.id.EditVie);
		start = (Button) findViewById(R.id.Main_startBtn);
		stop = (Button) findViewById(R.id.Main_stopBtn);
		 
		
		start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,MyService.class);
				intent.putExtra("data", edText.getText().toString());
				startService(intent);
			}
		});
		stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,MyService.class);
				stopService(intent);
			}
			
		});
	}
	 
}
   

不要忘记在MainFase里进行注册



使用BindService方法 启动服务

BindService案例代码
与saterService一样需要实现service
package com.handlers;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class MainService extends Service {

	/**
	 * 实现一个IBinder 实现里面的方法
	 */
	private IBinder myBinder = new Binder() {
		public String getInterfaceDescriptor() {
			return "MyService";

		};
	};
/**
 * 返回这个IBinder类
 */
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return this.myBinder;
	}

}
设置点击事件然后实现bindService方法 ,里面有三个参数
1,
intent
2,conn  这个需要实现ServiceConnection
3,flag 这是个Context, 一般使用 Context.BIND_AUTO_CREATE
package com.handlers;

import com.example.text_scort_android.R;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
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 TextView textView;
	private Button start,stop;
	public Handler handler  ;
	private MyBinder binder = new MyBinder();
	
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
			Toast.makeText(getApplicationContext(), "UnConnection", 0).show();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			binder = (MyBinder) service;
			binder.Middle(getApplication());
		}
	};
	 

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView = (TextView) findViewById(R.id.TextVie);
		start = (Button) findViewById(R.id.Main_startBtn);
		stop = (Button) findViewById(R.id.Main_stopBtn);
		 
		start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				bindService(new Intent(MainActivity.this,MainService.class), connection, Context.BIND_AUTO_CREATE);
			}
		});
		stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				binder.Middle(getApplication());
			}
			
		});
	}
	 
}
   

通过绑定Service操作进行操作

 <pre name="code" class="java">package com.text.service;

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

/**
 * 启动服务传递参数
 * 
 * @author Administrator
 *
 */
public class MyBindService extends Service {

	private String data;
	private boolean flag = true;

	/**
	 * 返回一个Binder类的对象,在调用的时候就是调用这个对象
	 */
	
	@Override
	public IBinder onBind(Intent intent) {
		return new Binders();
	}
	/**
	 * 定义一个类继承Binder,这个类是Binder类型,与MainActivity中的ServiceConnection中succeed的参数service是一个(可以这么理解)
	 * @author Administrator
	 *
	 */
	public class Binders extends Binder{
		public void setData(String data){
			MyBindService.this.data = data;
		}
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		data = intent.getStringExtra("data");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
	 new Thread(){
		 public void run() {
			 while (flag) {
				 System.out.println(data+"------");
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		 };
	 }.start();
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		flag = false;
	}

}

在Service的onBind方法中绑定上一个中间的类,Activity不可以直接操作Service但是可以间接地操作一个Bind类来操作service。
</pre><br />在Activity中设置点击按钮启动<pre name="code" class="java">case R.id.Main_Bind:
            bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
            break;
bindService里面有三个参数 1,Intent 2, Connection 3,flag
Intent就是和startService一样
Connection需要实现ServiceConnection
flag:BIND_AUTO_CREATE
这样就把Bind绑定到服务了
    /**
     * 实现一个Connection方法
     */
    private ServiceConnection connection = new ServiceConnection() {
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            
        }
        
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            binders = (Binders) service;
        }
    };
在onServiceConnection方法中实例化bind类 指向service,然后实现bind里面的方法
值得注意的是:方法里面的参数IBander ,这个参数和Service里IBinder方法是一个。
    case R.id.Main_Sync:
            if (binders != null) {
                //向Binder对象传递参数
                binders.setData(edText.getText().toString());
            }
            break;

设置一个按钮操作Service就可以了。

Bind类中如果有其他的方法不想暴露
那么可是使用接口
定义一个接口 由代码中的bind类实现,然后在onServiceConnection方法中使用接口的方法就可以了

完整代码:
package com.text;

import com.example.android_servicetext.R;
import com.text.service.MyBindService;
import com.text.service.MyBindService.Binders;
import com.text.service.MyService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener {
	private Button start, stop, bind, unbind,sync;
	private EditText edText;
	private Intent intent,bindIntent;
	private Binders binders;
	/**
	 * 实现一个Connection方法
	 */
	private ServiceConnection connection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binders = (Binders) service;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		start = (Button) findViewById(R.id.Main_satrt);
		stop = (Button) findViewById(R.id.Main_stop);
		bind = (Button) findViewById(R.id.Main_Bind);
		sync = (Button) findViewById(R.id.Main_Sync);
		unbind = (Button) findViewById(R.id.Main_UnBind);
		start.setOnClickListener(this);
		sync.setOnClickListener(this);
		stop.setOnClickListener(this);
		bind.setOnClickListener(this);
		unbind.setOnClickListener(this);
		edText = (EditText) findViewById(R.id.Main_edText);

	}

	@Override
	public void onClick(View v) {
		intent = new Intent(MainActivity.this, MyService.class);
		bindIntent = new Intent(MainActivity.this, MyBindService.class);
		switch (v.getId()) {
		case R.id.Main_satrt:
			intent.putExtra("data", edText.getText().toString());
			startService(intent);
			break;

		case R.id.Main_stop:
			stopService(intent);
			break;
		case R.id.Main_Bind:
			bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
			break;
		case R.id.Main_UnBind:
			unbindService(connection);
			break;
			//同步数据
		case R.id.Main_Sync:
			if (binders != null) {
				//向Binder对象传递参数
				binders.setData(edText.getText().toString());
			}
			break;
		}

	}

}

package com.text.service;

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

/**
 * 启动服务传递参数
 * 
 * @author Administrator
 *
 */
public class MyBindService extends Service {

	private String data;
	private boolean flag = true;

	/**
	 * 返回一个Binder类的对象,在调用的时候就是调用这个对象
	 */
	
	@Override
	public IBinder onBind(Intent intent) {
		return new Binders();
	}
	/**
	 * 定义一个类继承Binder,这个类是Binder类型,与MainActivity中的ServiceConnection中succeed的参数service是一个(可以这么理解)
	 * @author Administrator
	 *
	 */
	public class Binders extends Binder{
		public void setData(String data){
			MyBindService.this.data = data;
		}
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		data = intent.getStringExtra("data");
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onCreate() {
		super.onCreate();
	 new Thread(){
		 public void run() {
			 while (flag) {
				 System.out.println(data+"------");
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		 };
	 }.start();
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		flag = false;
	}

}

AIDL:


本地服务就不多说了
远程服务:
首先是startService的一个App

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		startService(new Intent(MainActivity.this,AppService.class));
	}

	 @Override
	protected void onDestroy() {
		super.onDestroy();
		stopService(new Intent(MainActivity.this,AppService.class));
	}
}

package com.service_app.service;

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

public class AppService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("Create===========");
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("Destory===========");
	}

}
一定要在Manifest里设置好权限问题
    <service
            android:name="com.service_app.service.AppService"
            android:enabled="true"
            android:process=":remote" 
            android:exported="true" >
            <action android:name="com.service_app.service.AppService" />
        </service>

在另一个app中
package com.another.aidl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
	private Button start, stop;
	private Intent Serviceintent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		start = (Button) findViewById(R.id.Main_StartBtn);
		stop = (Button) findViewById(R.id.Main_StopBtn);
		start.setOnClickListener(this);
		stop.setOnClickListener(this);
		Serviceintent = new Intent();
		/**
		 * 这里第一个参数是被动服务的包名
		 * 第二个参数是被启动服务的名
		 */
		Serviceintent.setComponent(new ComponentName("com.service_app",
				"com.service_app.service.AppService"));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.Main_StartBtn:
			startService(Serviceintent);
			break;

		case R.id.Main_StopBtn:
			stopService(Serviceintent);
			break;
		}
	}

}

一定要设置好权限问题不然会一直报错



服务绑定方式有两种:
本地服务:代码在一个工程中
远程服务:在不同的工程中


首先创建一个.aidl文件,创建好之后部署一下,就会在gen目录下生成对象的.java文件,其他与绑定本地的一样,只是使用了.aidl文件

public class AppService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		/**
		 * 在onBind方法中返回.aidl接口
		 */
		return new AIDL_Service.Stub() {
			
			@Override
			public void basicTtypes() throws RemoteException {
				// TODO Auto-generated method stub
				
			}
		};
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("Create===========");
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("Destory===========");
	}

}

case R.id.Main_BindBtn:
			bindService(Serviceintent, conn , Context.BIND_AUTO_CREATE);
			break;
		case R.id.Main_UnBindBtn:
			unbindService(conn);
			break;






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值