Android—Service详解
Service是Android四大组件之一,运用极为广泛,是一个APP无法缺少的重要一环,今天讲讲其应用—模拟抽奖实例

Android—Service

  • 什么是Service
  • Service的基本用法
  • Service分类及生命周期
  • Service实例模拟点击进行抽奖

什么是Service

什么是Service: Service能够在后台长时间运行,并且没有用户界面的应用程序组件 如:后台下载文件,播放音乐

Service的基本用法

创建MyService 继承自Service

Exported表示其他组件能不能调用该Service
Enabled表示Service能不能被实例化

配置Service
创建时会自动配置
在AndroidManifest.xml文件下可查看如:

<service    android:name=".MyService"    android:enabled="true"    android:exported="true"></service>

只有需重写常用的3个方法
onCreate() Service创建时调用
onStartCommand(Intent intent, int flags, int startId) 每次启动Service时调用的
onDestroy() Service销毁时调用

Service分类及生命周期

1、Started Service生命周期
要点:
Activity中调用startService()服务Service
Activity中调用stopService()停止Service
Service调用stopSelf()停止Service
生命周期:

startService()-->onCreate()-->onStartCommand()-->Service运行stopSelf||stopService()-->停止Service-->onDestroy()-->Service销毁


2、Bound Service
特点:Activity与Service绑定在一起, 进行交换数据
生命周期:

bindService()-->onCreate()-->onBind()-->绑定到ServiceunbindService()-->解除绑定-->onUnbind()-->onDestroy()-->Service销毁


实现Bound Service的基本步骤:
Service类中:
1、在创建的Service类中重写onbind方法让其返回2、中的的IBinder对象 用于通信
2、创建内部类继承自Binder类
Activity中:
具体看实例代码。

Service实例模拟点击进行抽奖

具体长这样

MyService类,具体请看代码解析

package com.example.test;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import java.util.ArrayList;import java.util.List;import java.util.Random;public class MyService extends Service {    public MyService() {    }    @Override    public void onCreate() {        super.onCreate();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();    }    @Override    public IBinder onBind(Intent intent) {        return new Mybind();                  //返回 Mybind()对象    }    //匿名内部类 获取MyService对象和状态    public class Mybind extends Binder {        public MyService getservice() {            return MyService.this;        //返回当前的service类        }    }/***********************设定奖励********2/10的机会*******************/    public List reward() {        List list = new ArrayList();        for (int i = 0; i < 8; i++) {            int n = new Random().nextInt(10)+1;  //1到10的整数            if (n == 1) {                String str = "奖励拾元";                list.add(str);            } else if (n == 2) {                String str = "奖励伍元";                list.add(str);            } else {                String str = "谢谢惠顾";                list.add(str);            }        }        return list;    }}

MainActivity类,具体看代码

package com.example.test;import androidx.appcompat.app.AppCompatActivity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.util.List;public class MainActivity extends AppCompatActivity {     MyService myService;     Button one;    int text[]=new int[]{R.id.text1,R.id.text2,R.id.text3,R.id.text4,                         R.id.text5,R.id.text6,R.id.text7,R.id.text8};     /****************创建ServiceConnection 连接对象**************/     private ServiceConnection connection=new ServiceConnection() {         @Override         public void onServiceConnected(ComponentName name, IBinder service) {                myService=((MyService.Mybind)service).getservice();         }         @Override         public void onServiceDisconnected(ComponentName name) {         }     };     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         one=findViewById(R.id.one);        one.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                List list=myService.reward();                for (int i=0;i<list.size();i++){                    TextView textView=findViewById(text[i]);                    textView.setText(list.get(i).toString());                }            }        });    }    /************************当该Activity开启时,与Service绑定****************************/    @Override    protected void onStart() {        super.onStart();        Intent intent=new Intent(this,MyService.class);        bindService(intent,connection,BIND_AUTO_CREATE);  //第三个参数表示是否自动创建Service,BIND_AUTO_CREATE将自动创建,0将不自动创建    }    /************************当该Activity停止时时,与Service解除绑定****************************/    @Override    protected void onStop() {        super.onStop();        unbindService(connection);    }}

布局代码:

<?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:paddingBottom="120dp"    android:paddingTop="120dp"    android:paddingLeft="30dp"    android:paddingRight="30dp"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity"    >    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="horizontal"        android:layout_weight="1"        >        <TextView            android:id="@+id/text1"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />        <TextView            android:id="@+id/text2"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />        <TextView            android:id="@+id/text3"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="horizontal"        android:layout_weight="1"        >        <TextView            android:id="@+id/text4"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />        <Button            android:id="@+id/one"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:gravity="center"            android:text="再来一次"            android:textSize="20dp"            android:background="#DF2E66"            />        <TextView            android:id="@+id/text5"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="horizontal"        android:layout_weight="1"        >        <TextView            android:id="@+id/text6"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />        <TextView            android:id="@+id/text7"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />        <TextView            android:id="@+id/text8"            android:layout_height="match_parent"            android:layout_weight="1"            android:layout_width="match_parent"            android:background="#FDD835"            android:gravity="center"            android:textSize="25dp"            />    </LinearLayout></LinearLayout>

更多相关文章

  1. android RxJava(RxAndroid)的简单使用
  2. IOS之UITabBarViewController用法
  3. Android中为APP创建快捷方式的原理(自己的理解)
  4. :Android模拟器的基本操作
  5. 使用html,javascript,css,phonegap创建开发android应用程序
  6. 人人网官方Android客户端源码分析(1)
  7. Android读写XML(下)——创建XML文档
  8. Xamarin.Android使用教程之创建第一个Android应用程序
  9. Android读写XML(下)——创建XML文档

随机推荐

  1. Android(安卓)L中的RecyclerView 、CardV
  2. Theme(主题) Style(风格)
  3. android音频口通信——2FSK信号调制
  4. 自定义 Android(安卓)Preference——Spin
  5. android关于EditText取消默认焦点及触摸
  6. react-natvie vscode真机调试[Android]
  7. Android(安卓)HTTPS认证之Volley封装
  8. 如何实现手势缩放图片
  9. Android(安卓)SDK下载和更新失败的解决方
  10. android 自定义ButtonTab , ActivityGrou