iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >AndroidService开发应用实例
  • 416
分享到

AndroidService开发应用实例

AndroidServiceAndroidService开发 2022-12-16 12:12:48 416人浏览 八月长安
摘要

目录Service 开发应用BindServiceIntentServiceService 开发应用 在后台长时间运行,没有界面UI, 在后台下载文件和获取用户GPS信息 Servi

Service 开发应用

在后台长时间运行,没有界面UI, 在后台下载文件和获取用户GPS信息

  • Service: 分为 startService 和 BoundService;
  • 只有Activity 调用startService才会通知服务启动, BoundService只Activity bindService 进行启动。
  • Service中Export 和Enable两个属性, Export 应用组件能不能调用被Service, Enable: 表示Service能不能被实例化。
  • 重写onBind ,onCreate,onStartCommand,onDestory 这个四个方法。
  • 在调用Service 时候判断本Service是否在正在运行
// 需要在XML文件中配准Service Bound
   <service
            Android:name=".MusicService"
            android:enabled="true"
            android:exported="true"></service>
  public boolean isRunning() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfoArrayList
                = (ArrayList< ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(10);
        for(int i=0;i <runningServiceInfoArrayList.size();i++){
            if(runningServiceInfoArrayList.get(i).service.getClassName().toString().equals("com.example.myapplication.MyService")) {
                return true;
            }
        }
        return false;
    }
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ImageButton btn_play = (ImageButton) findViewById(R.id.btn_play);//获取“播放/停止”按钮
        //启动服务与停止服务,实现播放背景音乐与停止播放背景音乐
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MusicService.isPlay == false) {   //判断音乐播放的状态
                    startService(new Intent(MainActivity.this, MusicService.class));  //启动服务,从而实现播放背景音乐
                    //更换播放背景音乐图标
                    ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.play, null));
                } else {
                    stopService(new Intent(MainActivity.this, MusicService.class));  //停止服务,从而实现停止播放背景音乐
                    //更换停止背景音乐图标
                    ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.stop, null));
                }
            }
        });
    }
    @Override
    protected void onStart() {  //实现进入界面时,启动背景音乐服务
       startService(new Intent(MainActivity.this, MusicService.class));  //启动服务,从而实现播放背景音乐
        super.onStart();
    }
}
package com.example.myapplication;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class MusicService extends Service {
    public MusicService() {
    }
    static boolean isPlay =false;
    private MediaPlayer player;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 判断播放状态
        if(player.isPlaying()) {
            player.start();
            isPlay = player.isPlaying();
        }
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onCreate() {
        // 创建MediaPlay对象,加载播放音频对象
        player = MediaPlayer.create(this,R.raw.music);
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        player.stop();
        isPlay = player.isPlaying();
        player.release();
        super.onDestroy();
    }
}

注意 在Android 8.0 后不允许在后台创建Service 上面有问题 需要调整

BindService

  • Service对象中 创建一个MyBinder类型的绑定器, 返回其绑定对象
  • Activity中 ServiceConnection 重写其中方法,在此方法中获取Service独享
package com.example.myapplication;
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 {
    BinderService binderService;   //声明BinderService
    //文本框组件ID
    int[] tvid = {R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4, R.id.textView5,
            R.id.textView6, R.id.textView7};
    // 创建ServiceConnection 对象
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binderService =  ((BinderService.MyBinder) iBinder).getService();
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn_random = (Button) findViewById(R.id.btn);  //获取随机选号按钮
        btn_random.setOnClickListener(new View.OnClickListener() {  //单击按钮,获取随机彩票号码
            @Override
            public void onClick(View v) {
                List number = binderService.getRandomNumber();  //获取BinderService类中的随机数数组
                for (int i = 0; i < number.size(); i++) {  //遍历数组并显示
                    TextView tv = (TextView) findViewById(tvid[i]);  //获取文本框组件对象
                    String strNumber = number.get(i).toString();     //将获取的号码转为String类型
                    tv.setText(strNumber);  //显示生成的随机号码
                }
            }
        });
    }
    @Override
    protected void onStart() {  //设置启动Activity时与后台Service进行绑定
        super.onStart();
        Intent intent = new Intent(this, BinderService.class);  //创建启动Service的Intent
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);           //绑定指定Service
    }
    @Override
    protected void onStop() {  //设置关闭Activity时解除与后台Service的绑定
        super.onStop();
        unbindService(serviceConnection);    //解除绑定Service
    }
}
package com.example.myapplication;
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 BinderService extends Service {
    public BinderService() {
    }
    // 创建MyBinder 内部类
    public class MyBinder extends Binder {
        public BinderService getService() {
            return BinderService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new MyBinder();
    }
    public List getRandomNumber() {  //创建获取随机号码的方法
        List resArr = new ArrayList();   //创建ArrayList数组
        String strNumber="";
        for (int i = 0; i < 7; i++) {  //将随机获取的数字转换为字符串添加到ArrayList数组中
            int number = new Random().nextInt(33) + 1;
            //把生成的随机数格式化为两位的字符串
            if (number<10) {  //在数字1~9前加0
                strNumber = "0" + String.valueOf(number);
            } else {
                strNumber=String.valueOf(number);
            }
            resArr.add(strNumber);
        }
        return resArr;  //将数组返回
    }
    @Override
    public void onDestroy() {  //销毁该Service
        super.onDestroy();
    }
}

IntentService

IntentService VS 普通Service区别:

  • 在普通service进行IO请求或者是 Http耗时请求,会让Android在此等待,所以使用 IntentService 解决 耗时严重的 HTTP请求。
  • 普通的Service 不能自动开启线程 和 自动停止服务
  • 所以IntentService 解决普通Service 这两个问题

到此这篇关于Android Service开发应用实例的文章就介绍到这了,更多相关Android Service内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: AndroidService开发应用实例

本文链接: https://www.lsjlt.com/news/175029.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • AndroidService开发应用实例
    目录Service 开发应用BindServiceIntentServiceService 开发应用 在后台长时间运行,没有界面UI, 在后台下载文件和获取用户GPS信息 Servi...
    99+
    2022-12-16
    Android Service Android Service开发
  • ZooKeeper开发实际应用案例实战
    目录项目背景介绍面临问题如何解决代码讲解数据服务器检索服务器总结附:完整代码数据服务端代码检索服务端代码ZooKeeper入门教程一简介与核心概念 ZooKeeper入门教程二在单机...
    99+
    2024-04-02
  • Spring Boot应用开发初探与实例讲解
    Spring Boot是由Pivotal团队提供的全新Spring开发框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。 从它的名字可以看出,Spring Boot...
    99+
    2024-04-02
  • PHP开发缓存的实际应用案例分析
    PHP开发缓存的实际应用案例分析引言:随着互联网的快速发展,网站的访问量大幅增加。为了提高网站的性能和响应速度,开发人员需要使用缓存来减少数据库查询,加快数据访问速度。本文将重点介绍PHP中缓存的实际应用案例,包括数据缓存和页面缓存,并提供...
    99+
    2023-11-07
    缓存 开发 PHP 关键词:
  • WebSocket在实时游戏开发中的应用案例
    引言:随着网络技术的不断发展,实时游戏的需求也日益增长。传统的HTTP协议在实时游戏的场景下往往无法满足即时性和实时性的要求。而WebSocket作为一种新兴的通信协议,在实时游戏开发中得到了广泛应用。本文将以具体的案例和示例代码来探讨We...
    99+
    2023-10-21
    websocket 应用案例 实时游戏
  • vue开发应用的示例分析
    这篇文章将为大家详细讲解有关vue开发应用的示例分析,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。使用 vux UI组件库使用 vue-navigation...
    99+
    2024-04-02
  • k3cloud开发实例
    开发工具        Visual studio 2012        IE插件Silverlight5        SQLServer 2008R2 或 Oracle 11G R2        跟踪工具(HttpWatchPro6...
    99+
    2023-01-31
    实例 k3cloud
  • 用Eclipse开发Struts实例-G
    十、建立读取留言信息的Action类 1、建立GuestBook的JavaBean类 package com.meixin.beans; public class Guestbook {   private ...
    99+
    2023-01-31
    实例 Eclipse Struts
  • Android开发Flutter 桌面应用窗口化实战示例
    目录前言一、应用窗口的常规配置应用窗口化自定义窗口导航栏美化应用窗口二、windows平台特定交互注册表操作执行控制台指令实现应用单例三、桌面应用的交互习惯按钮点击态获取应用启动参数...
    99+
    2024-04-02
  • 使用Docker开发python Web应用的案例
    小编给大家分享一下使用Docker开发python Web应用的案例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!本文中,我将尝试展示用Docker开发pytho...
    99+
    2023-06-07
  • Spring Boot应用开发的示例分析
    这篇文章主要介绍了Spring Boot应用开发的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。Spring Boot是由Pivotal团队提供的全新Spring开发...
    99+
    2023-06-20
  • ASP 实时框架开发技术,有哪些实际应用案例?
    ASP 实时框架是一种用于构建实时 Web 应用程序的技术。它使用了一系列高效的开发工具和技术,使开发人员能够轻松地构建出高效、可靠、可扩展的实时 Web 应用程序。本文将深入探讨 ASP 实时框架的开发技术,并介绍一些实际应用案例。 一...
    99+
    2023-07-23
    实时 框架 开发技术
  • spring3+mbatis3开发实例
    最近一直在深入了解struts2,spring,hibernate以及mybatis框架,通过查看这些框架的源码和官方文档,发现自己对于这些框架的原理,使用有了更深的理解,那么今天我给大家带来的是运用spring和mybatis这两个框架来...
    99+
    2023-01-31
    实例
  • vue3组件化开发之可复用性的应用实例详解
    目录自定义指令基本结构自定义 v-loading 指令插件基本结构实现一个全局状态管理插件Teleport 传送相关链接总结可复用性也是组件化开发的一个优势,能让代码更加简洁优雅、方...
    99+
    2024-04-02
  • 重定向在Java开发中的实际应用案例分享?
    重定向是Web开发中非常重要的一项技术,它可以使得网站的页面跳转更加灵活,同时也可以提高网站的安全性。在Java开发中,重定向的实际应用非常广泛,下面我们来分享一些实际应用案例。 用户登录验证 在Web开发中,用户登录验证是非常重要的一...
    99+
    2023-06-02
    重定向 spring numy
  • Go语言应用开发的最新趋势与应用案例
    随着技术的不断发展,Go语言作为一种高效、易用的编程语言在应用开发领域中日益受到关注和应用。本篇文章将探讨Go语言应用开发的最新趋势以及一些具体的应用案例,并提供相关的代码示例进行展示...
    99+
    2024-03-01
    go语言 应用案例 开发趋势 区块链 区块链技术
  • .NET6开发TodoList应用之实现ActionFilter
    目录需求目标原理与思路实现验证总结需求 Filter在.NET Web API项目开发中也是很重要的一个概念,它运行在执行MVC响应的Pipeline中执行,允许我们将一些可以在多个...
    99+
    2024-04-02
  • android studio开发app实例
    以下是一个简单的Android Studio开发App的实例: 打开Android Studio,并创建一个新项目。 选择一个适当的应用程序名称和包名称,然后选择目标API级别和默认Activity的模板。 在MainActivity...
    99+
    2023-09-05
    android studio android ide
  • Laravel开发实例分析
    本篇内容主要讲解“Laravel开发实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Laravel开发实例分析”吧!   准备开发环境   原教程使用...
    99+
    2024-04-02
  • H5、CSS3、Mui开发实例
    前言    因进度需要,所以本人从一个服务端、架构暂时变成了一个前端开发者!对于前端的理解    所谓“万变不离其宗”,就是这样一个道理,写惯了服务端,当接触前端以前总觉得很难,但是当我真正开始写的时候,发觉一如既往的简单,就是简单的jqu...
    99+
    2023-01-31
    实例 Mui
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作