android studio后台服务使用详解

 更新时间:2022年08月11日 16:43:49   作者:冰山丶一角  
这篇文章主要为大家详细介绍了android studio后台服务,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Service 是 Android 系统的服务组件,适用于开发没有用户界面且长时间在后台运行的功能。通过本次试验了解后台服务的基本原理,掌握本地服务的使用方法。

1、创建一个Service服务用来完成简单的求和和比较大小的数学运算。
2、创建Activity并调用该数学Service

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="第一个数:">
 
        </TextView>
 
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:id="@+id/firstnum"
            android:inputType="number"
            android:digits="1234567890.">
 
        </EditText>
    </LinearLayout>
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="第二个数"/>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:id="@+id/second"
            android:inputType="number"
            android:digits="1234567890."/>
    </LinearLayout>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bind"
        android:text="绑定"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/add"
        android:text="求和"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/compare"
        android:text="比较大小"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/unbind"
        android:text="解除绑定"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/out"/>
 
 
</LinearLayout>
 
 
</androidx.constraintlayout.widget.ConstraintLayout>

MathService.java

package com.example.serviceexperiment;
 
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
 
public class MathService extends Service {
    //服务绑定
    final IBinder mBinder=new LocalBinder();
    public class LocalBinder extends Binder {
        MathService getService() {
            return MathService.this;
        }
    }
    public MathService() {
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }
    public boolean onUnbind(Intent intent){
        Toast.makeText(this,"取消本地绑定",Toast.LENGTH_SHORT).show();
        return false;
    }
    public Double Add(Double a,Double b){
        return a+b;
    }
    public boolean Compare(Double a,Double b){
        if(a>b){
            return true;
        };
        return false;
    }
}

MainActicity.java

package com.example.serviceexperiment;
 
import androidx.appcompat.app.AppCompatActivity;
 
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.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
    private MathService mathService;
    private boolean isBound=false;
    TextView labelView;
    EditText firstnum;
    EditText secondnum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        labelView=(TextView)findViewById(R.id.out);
        labelView.setText("两个数默认值都为0");
        firstnum=(EditText)findViewById(R.id.firstnum);
        secondnum=(EditText)findViewById(R.id.second);
        Button bindButton=(Button)findViewById(R.id.bind);
        Button unbindButton=(Button)findViewById(R.id.unbind);
        Button addButton=(Button)findViewById(R.id.add);
        Button compareButton=(Button)findViewById(R.id.compare);
        bindButton.setOnClickListener(new View.OnClickListener() {//绑定按钮
            @Override
            public void onClick(View view) {
                if(!isBound){
                    final Intent serviceIntent=new Intent(MainActivity.this,MathService.class);
                    bindService(serviceIntent,mConnection,Context.BIND_AUTO_CREATE);
                    isBound=true;
                    Toast.makeText(MainActivity.this,"本地绑定:MathService",Toast.LENGTH_SHORT).show();
                }
            }
        });
        unbindButton.setOnClickListener(new View.OnClickListener() {//解绑按钮
            @Override
            public void onClick(View view) {
                if(isBound){
                    isBound=false;
                    unbindService(mConnection);
                    mathService=null;
 
                    Toast.makeText(MainActivity.this,"取消本地绑定:MathService",Toast.LENGTH_SHORT).show();
                }
            }
        });
        addButton.setOnClickListener(new View.OnClickListener() {//调用服务加法
            @Override
            public void onClick(View view) {
 
                if(mathService==null){
                    Toast.makeText(MainActivity.this,"未绑定服务:MathService",Toast.LENGTH_SHORT).show();
                    return;
                }
 
                String firsttext=firstnum.getText().toString();
                Double a= 0.0;
                if(firsttext.length()!=0){
                    a=Double.parseDouble(firsttext);
                }
 
                String secondtext=secondnum.getText().toString();
                Double b= 0.0;
                if(secondtext.length()!=0){
                    b=Double.parseDouble(secondtext);
                }
                Double result=mathService.Add(a,b);
                String msg=String.valueOf(a)+"+"+String.valueOf(b)+"="+String.valueOf(result);
                labelView.setText(msg);
 
            }
        });
        compareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mathService==null){
                    Toast.makeText(MainActivity.this,"未绑定服务:MathService",Toast.LENGTH_SHORT).show();
                    return;
                }
 
                String firsttext=firstnum.getText().toString();
                Double a= 0.0;
                if(firsttext.length()!=0){
                    a=Double.parseDouble(firsttext);
                }
 
                String secondtext=secondnum.getText().toString();
                Double b= 0.0;
                if(secondtext.length()!=0){
                    b=Double.parseDouble(secondtext);
                }
                boolean result=mathService.Compare(a,b);
                String msg;
                if(result){
 
                    msg=String.valueOf(a)+"和"+String.valueOf(b)+"中最大的数是"+String.valueOf(a);
                }else{
                    msg=String.valueOf(a)+"和"+String.valueOf(b)+"中最大的数是"+String.valueOf(b);
                }
                labelView.setText(msg);
            }
        });
    }
    private ServiceConnection mConnection=new ServiceConnection() {//绑定
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mathService=((MathService.LocalBinder)iBinder).getService();
        }
 
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mathService=null;
        }
    };
}

AndroidMainfest.xml中加入

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 修改Android中hosts文件的步骤详解

    修改Android中hosts文件的步骤详解

    有朋友问Android怎么修改Hosts?对于这个问题,由于手头并没有Android设备,所以只能从网上搜罗了方法并总结出来,下面这篇文章主要介绍了修改Android中hosts文件的步骤,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-02-02
  • Android中Hilt的使用详解

    Android中Hilt的使用详解

    Hilt 是 Android 的依赖项注入库,可减少在项目中执行手动依赖项注入的样板代码,本文就来为大家介绍一下Hilt的具体使用吧,希望对大家有所帮助
    2023-06-06
  • Android基于Toolbar实现顶部标题栏及后退键

    Android基于Toolbar实现顶部标题栏及后退键

    这篇文章主要介绍了Android基于Toolbar实现顶部标题栏及后退键,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • Android Studio中使用lambda表达式的方法

    Android Studio中使用lambda表达式的方法

    这篇文章主要介绍了Android Studio中使用lambda表达式的方法,需要的朋友可以参考下
    2017-06-06
  • Android冷启动实现app秒开的实现代码

    Android冷启动实现app秒开的实现代码

    本篇文章主要介绍了Android冷启动实现app秒开的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • Android中二维码的扫描和生成(使用zxing库)

    Android中二维码的扫描和生成(使用zxing库)

    ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口,下面这篇文章主要给大家介绍了关于Android中二维码扫描和生成的相关资料,主要使用的zxing库,需要的朋友可以参考下
    2022-09-09
  • Android利用代码控制设备上其他音乐播放器的方法

    Android利用代码控制设备上其他音乐播放器的方法

    这篇文章主要给大家介绍了关于Android利用代码如何控制设备上其他音乐播放器的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-06-06
  • Android开发实现长按返回键弹出关机框功能

    Android开发实现长按返回键弹出关机框功能

    这篇文章主要介绍了Android开发实现长按返回键弹出关机框功能,涉及Android针对长按事件的响应与处理相关操作技巧,需要的朋友可以参考下
    2017-09-09
  • Android ViewPager画廊效果详解及实例

    Android ViewPager画廊效果详解及实例

    这篇文章主要介绍了Android ViewPager画廊效果详解及实例的相关资料,这里提供实例代码及实现效果图,具有参考价值,需要的朋友可以参考下
    2016-12-12
  • Android Studio 引用外部依赖时报错的解决方法

    Android Studio 引用外部依赖时报错的解决方法

    这篇文章主要介绍了Android Studio报错Unable to resolve dependency for':app@release/compileClasspath':无法引用任何外部依赖的解决办法,需要的朋友可以参考下
    2018-01-01

最新评论