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

Android—Service

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

什么是Service

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

Service的基本用法

创建MyService 继承自Service
Android—Service详解—模拟点击抽奖(2020.7.3)_第1张图片
Exported表示其他组件能不能调用该Service
Enabled表示Service能不能被实例化
Android—Service详解—模拟点击抽奖(2020.7.3)_第2张图片
配置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销毁

Android—Service详解—模拟点击抽奖(2020.7.3)_第3张图片
2、Bound Service
特点:Activity与Service绑定在一起, 进行交换数据
生命周期:

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

Android—Service详解—模拟点击抽奖(2020.7.3)_第4张图片
实现Bound Service的基本步骤:
Service类中:
1、在创建的Service类中重写onbind方法让其返回2、中的的IBinder对象 用于通信
2、创建内部类继承自Binder类
Activity中:
具体看实例代码。

Service实例模拟点击进行抽奖

具体长这样
Android—Service详解—模拟点击抽奖(2020.7.3)_第5张图片
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 Volley框架使用详解
  2. 详解Android中一些SQLite的增删改查操作
  3. Android编程之文件的读写实例详解
  4. android notification,notificationmanager详解
  5. Android三大动画详解
  6. Android与JS之间跨平台异步调用实例详解

随机推荐

  1. tools:context =“activityname”布局文
  2. [原]android 中如何飞行模式的几个操作
  3. Android 图片缩放与旋转
  4. 进度条及拖动条背景颜色设置(progressDraw
  5. Android windowSoftInputMode属性解析
  6. mapView 和textView布局
  7. Android 中文 API (100) —— ScrollView
  8. android---------ndk中的各个版本的下载
  9. android原生音乐播放器界面字体显示不全
  10. android开发之Seekbar