Serivice启动方式案例
1.案例1:-start方式启动
1.1创建服务
//服务类
public class MyService extends Service {
//创建服务调用一次
@Override
public void onCreate() {
System.out.println("onCreate");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
super.onCreate();
}
//创建服务
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//startId ONLY
System.out.println("onStartCommend"+startId);
Toast.makeText(this, "onStartCommend"+startId, Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
// 服务销毁
@Override
public void onDestroy() {
//startId ONLY
System.out.println("onDestory");
Toast.makeText(this, "onDestory", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
1.2注册服务
<!-- 注册服务-->
<service android:name=".MyService"
android:exported="true">
<intent-filter>
<action android:name="com.lxz.app10Service"/>
</intent-filter>
</service>
1.3设置布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="启动服务-显式"
android:textSize="30dp"
android:onClick="startService1"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="启动服务-隐式"
android:textSize="30dp"
android:onClick="startService2"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="停止服务1"
android:textSize="30dp"
android:onClick="stopService11"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="停止服务2"
android:textSize="30dp"
android:onClick="stopService22"
/>
</LinearLayout>
1.4设置Java代码
- 设置按钮的事件监听
- 设置每个按钮注册服务的方式,stratService
- 设置服务的注销,stopService
//采用start的启动方式-采用隐式启动
public class MainActivity extends AppCompatActivity {
private Intent intent1=null;
private Intent intent2=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//启动服务-显式
public void startService1(View view) {
intent1=new Intent();
intent1.setClass(getApplicationContext(),MyService.class);
startService(intent1);
}
//启动服务-隐式
public void startService2(View view) {
intent2=new Intent();
intent2.setPackage("com.lxz.app10");
intent2.setAction("com.lxz.app10Service");
startService(intent2);
}
//停止服务
public void stopService11(View view) {
stopService(intent1);
}
//停止服务
public void stopService22(View view) {
stopService(intent2);
}
}
1.5效果图
2.案例2:-bind方式启动进行数据运算
1.使用Service进行求和和阶乘的运算。
2.参考代码
- Service代码
//用于计算的service
public class Calculate extends Service {
//便于调用结果
private MyBinder myBinder=new MyBinder();
//创建
@Override
public void onCreate() {
System.out.println("onCreate");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
super.onCreate();
}
//onBind
@Nullable
@Override
public IBinder onBind(Intent intent) {
//接收传递的数据
String str=intent.getStringExtra("code");
System.out.println("onBind---"+"code="+str);
Toast.makeText(this, "onBind---code="+str, Toast.LENGTH_SHORT).show();
return myBinder;
}
//解绑
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onUnbind");
Toast.makeText(this, "onUnbind", Toast.LENGTH_SHORT).show();
return false;
}
//销毁
@Override
public void onDestroy() {
System.out.println("onDestroy");
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
}
//内部类
class MyBinder extends Binder {
//返回Service对象
public Calculate getService(){
return Calculate.this;
}
}
//方法:求和
public int getSum(int i){
int sum=0;
for (int j=0;j<=i;j++){
sum+=j;
}
return sum;
}
//方法:求阶乘
public long getJieCheng(long i){
long sum=1;
for (long j=1;j<=i;j++){
sum*=j;
}
return sum;
}
}
- 注册信息
<service android:name=".Calculate" />
- 主布局文件代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CalculateActivity">
<EditText
android:id="@+id/textnumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入要计算的数字"
android:gravity="center"
android:textSize="30dp"
android:inputType="numberSigned"
android:maxLines="1"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="绑定服务"
android:textSize="30dp"
android:onClick="bindService11"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="求和"
android:textSize="30dp"
android:onClick="textgetSum"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="求阶乘"
android:textSize="30dp"
android:onClick="textgetJiecheng"
/>
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="输出信息"
android:textSize="30dp"
android:maxLines="1"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="解绑服务"
android:textSize="30dp"
android:onClick="unBindService11"
/>
</LinearLayout>
- 主布局文件的Java代码
//输出计算结果案例
public class CalculateActivity extends AppCompatActivity {
//是不是注册标志
private boolean flag=false;
//Service
Calculate service=null;
//连接对象
ConnectionUtil conn=null;
//Mybinder对象,用于获取Service
Calculate.MyBinder binder=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculate);
}
//解绑服务
public void unBindService11(View view) {
if (flag){
unbindService(conn);
flag=!flag;
}
else
{
Toast.makeText(getApplicationContext(), "暂为可解绑的服务!", Toast.LENGTH_SHORT).show();
}
}
//阶乘
public void textgetJiecheng(View view) {
if (flag){
TextView textView=findViewById(R.id.textnumber);
TextView result=findViewById(R.id.result);
if (textView.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(), "请输入有效数字!", Toast.LENGTH_SHORT).show();
}
else{
result.setText(service.getJieCheng( Long.parseLong(textView.getText().toString().trim()))+"");
}
}
else
{
Toast.makeText(getApplicationContext(), "请先绑定服务!", Toast.LENGTH_SHORT).show();
}
}
//求和
public void textgetSum(View view) {
if (flag){
TextView textView=findViewById(R.id.textnumber);
TextView result=findViewById(R.id.result);
if (textView.getText().toString().trim().equals("")){
Toast.makeText(getApplicationContext(), "请输入有效数字!", Toast.LENGTH_SHORT).show();
}
else{
result.setText(service.getSum( Integer.parseInt(textView.getText().toString().trim()))+"");
}
}
else
{
Toast.makeText(getApplicationContext(), "请先绑定服务!", Toast.LENGTH_SHORT).show();
}
}
//服务绑定
public void bindService11(View view) {
if (!flag){
conn=new ConnectionUtil();
Intent intent=new Intent();
intent.setClass(getApplicationContext(),Calculate.class);
intent.putExtra("code","200");
bindService(intent,conn,BIND_AUTO_CREATE);
flag=!flag;
}
else
{
Toast.makeText(getApplicationContext(), "请不要重复绑定!", Toast.LENGTH_SHORT).show();
}
}
//连接类
private class ConnectionUtil implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//获取binder对象
binder= (Calculate.MyBinder) iBinder;
//获取service
service=binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
binder=null;
service=null;
}
}
}
(5)效果图
3.案例3:-bind方式启动输入helloword
1.使用Service进行输出helloword。
2.参考代码
- 自定义服务类
//自定义服务
public class MyService extends Service {
//便于调用结果
private MyBinder myBinder=new MyBinder();
//创建
@Override
public void onCreate() {
System.out.println("onCreate");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
super.onCreate();
}
//onBind
@Nullable
@Override
public IBinder onBind(Intent intent) {
//接收传递的数据
String str=intent.getStringExtra("code");
System.out.println("onBind---"+"code="+str);
Toast.makeText(this, "onBind---code="+str, Toast.LENGTH_SHORT).show();
return myBinder;
}
//解绑
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onUnbind");
Toast.makeText(this, "onUnbind", Toast.LENGTH_SHORT).show();
return false;
}
//销毁
@Override
public void onDestroy() {
System.out.println("onDestroy");
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
}
//内部类
class MyBinder extends Binder{
//返回Service对象
public MyService getService(){
return MyService.this;
}
}
//方法
public void printHello(){
System.out.println("hello world!");
Toast.makeText(this, "hello world!", Toast.LENGTH_SHORT).show();
}
}
- 注册服务
<service android:name=".MyService" />
- 创建布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="绑定服务"
android:textSize="30dp"
android:onClick="bindService11"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="输出信息"
android:textSize="30dp"
android:onClick="bindService22"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="解绑服务"
android:textSize="30dp"
android:onClick="unBindService11"
/>
</LinearLayout>
- Service的启动类代码。
//启动服务
public class MainActivity extends AppCompatActivity {
MyService myService=null;
MyService.MyBinder binder=null;
ConnectionUtil conn=null;
private boolean Flag=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//绑定
public void bindService11(View view) {
if (!Flag){
//显式启动
Intent intent=new Intent();
intent.setClass(this,MyService.class);
//设置传递数据
intent.putExtra("code","200");
//创建连接对象
conn=new ConnectionUtil();
//绑定服务
bindService(intent,conn,BIND_AUTO_CREATE);
Flag=!Flag;
}
else {
Toast.makeText(getApplicationContext(), "服务已绑定!", Toast.LENGTH_SHORT).show();
}
}
//输出信息
public void bindService22(View view) {
if (Flag) {
myService.printHello();
}
else{
Toast.makeText(getApplicationContext(), "请绑定服务!", Toast.LENGTH_SHORT).show();
}
}
//解绑
public void unBindService11(View view) {
if (Flag){
unbindService(conn);
Flag=!Flag;
}
else{
Toast.makeText(getApplicationContext(), "暂无可解绑的服务!", Toast.LENGTH_SHORT).show();
}
}
//自定义连接类
private class ConnectionUtil implements ServiceConnection {
//服务连接
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder= (MyService.MyBinder) iBinder;
myService= binder.getService();
}
//服务解绑-被kill的时候才会调用
@Override
public void onServiceDisconnected(ComponentName componentName) {
binder=null;
myService=null;
}
}
}
- 效果图
4.案例-start和bind学习的案例
4.1目录结构
4.2注册信息
<!-- 注册Service-->
<service android:name=".service.MyService1"
android:exported="true">
<!-- 说明该Service被哪些Intent启动 -->
<intent-filter>
<action android:name="com.lxz.app9Service"/>
</intent-filter>
</service>
4.3自定义Service的代码
public class MyService1 extends Service {
/*
*
* 创建的时候被调用一次,调用完成之后会销毁
* */
@Override
public void onCreate() {
super.onCreate();
System.out.println("onCreate");
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
}
/*
* 采用startService启动服务的时候调用
* Intent是从客户端传来的数据
* flags是附加数据,表示启动的方式
*startId表示当前服务的唯一的ID的值
* */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "stratService"+startId, Toast.LENGTH_SHORT).show();
//服务编号每次启动的都是不一样的
System.out.println("服务编号"+startId);
return super.onStartCommand(intent, flags, startId);
}
MyBinder binder=new MyBinder();
@Nullable
@Override
/*
* 采用bind的方式启动的时候会被调用
* 返回值是一个IBinder的接口实现类对象(需要自己去定义)
* */
public IBinder onBind(Intent intent) {
System.out.println("onBind");
Toast.makeText(this, "onBind", Toast.LENGTH_SHORT).show();
//必须返回binder对象,不然的话是失败的
return binder;
}
/*
*
* 客户端调用unBindService的时候调用,断开改Service上连接的所有客户端
* */
@Override
public boolean onUnbind(Intent intent) {
System.out.println("onUnbind");
Toast.makeText(this, "onUnbind", Toast.LENGTH_SHORT).show();
return true;
}
/*
* 当Service被关闭/销毁的时候调用
* */
@Override
public void onDestroy() {
System.out.println("onDestory");
Toast.makeText(this, "onDestory", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
//IBinder内部类
public class MyBinder extends Binder {
//获取Service对象
public Service getService(){
return MyService1.this;
}
}
//方法:输出hello
public void printHello(){
Toast.makeText(this,"你好啊!",Toast.LENGTH_SHORT);
System.out.println("你好啊!");
}
}
4.4主布局文件代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="startService"
android:textSize="30dp"
android:onClick="startService1"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="startService(隐式)"
android:textSize="30dp"
android:onClick="startService2"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="stopService"
android:textSize="30dp"
android:onClick="stopService11"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="bindService1"
android:textSize="30dp"
android:onClick="bindService11"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="输出你好啊!"
android:textSize="30dp"
android:onClick="bindService22"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="unBindService"
android:textSize="30dp"
android:onClick="unBindService11"
/>
</LinearLayout>
4.5主布局文件的Java代码
//启动服务就类比启动Activity的做法
public class MainActivity extends AppCompatActivity {
Intent intent=null;
//继承Binder的内部类
MyService1.MyBinder myBinder=null;
//自定义服务
MyService1 bservice=null;
//自定义连接对象
ConnectionUtil conn=null;
//是不是绑定了
private boolean FLAG=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//方式一显式启动
public void startService1(View view) {
intent=new Intent(this,MyService1.class);
startService(intent);
}
//方式一隐式启动
public void startService2(View view) {
intent=new Intent();
//需要设置app的包名否则无效
intent.setPackage("com.lxz.app9");
intent.setAction("com.lxz.app9Service");
startService(intent);
}
//停止服务:
public void stopService11(View view) {
stopService(intent);
}
//采用服务绑定的方式
/*
* flages:0表示绑定的时候不自动创建Server对象,1(BIND_AUTO_CREATE)表示自动创建Service对象
* */
public void bindService11(View view) {
if (!FLAG)
{
intent=new Intent();
//需要设置app的包名否则无效
intent.setPackage("com.lxz.app9");
intent.setAction("com.lxz.app9Service");
conn=new ConnectionUtil();
bindService(intent,conn,BIND_AUTO_CREATE);
FLAG=!FLAG;
}
else
{
Toast.makeText(bservice, "请不要重复绑定", Toast.LENGTH_SHORT).show();
}
}
//调用输入你好的方法
public void bindService22(View view) {
if (FLAG) {
bservice.printHello();
}
else {
Toast.makeText(getApplicationContext(), "请绑定后使用!", Toast.LENGTH_SHORT).show();
}
}
//解除服务绑定
public void unBindService11(View view) {
if (FLAG)
{
unbindService(conn);
FLAG=!FLAG;
}
else{
Toast.makeText(getApplicationContext(), "暂无绑定的服务!", Toast.LENGTH_SHORT).show();
}
}
//创建连接对象
/*
* 实现连接服务
* */
private class ConnectionUtil implements ServiceConnection {
/*
* 绑定成功的时候调用
* IBinder iBinder就是onBind返回的binder对象
* */
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("onServiceConnected---服务连接");
//此时获取到的就是onBind返回的IBinder对象,myBinder拥有service的Context,从而可以调用Service中定义方法
myBinder=(MyService1.MyBinder)iBinder;
//获取Service对象
bservice= (MyService1) myBinder.getService();
}
/*
* 该方法只在Service 被破坏了或者被杀死的时候调用. 例如, 系统资源不足, 要关闭一些Services, 刚好连接绑定的 Service 是被关闭者之一, 这个时候onServiceDisconnected() 就会被调用.
* */
@Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("onServiceDisconnected---服务断开");
myBinder=null;
bservice=null;
}
}
}
4.6效果图
(1)start方式
(2)采用bind方式