網(wǎng)站首頁 編程語言 正文
Service 開發(fā)應(yīng)用
在后臺長時間運行,沒有界面UI, 在后臺下載文件和獲取用戶GPS信息
- Service: 分為 startService 和 BoundService;
- 只有Activity 調(diào)用startService才會通知服務(wù)啟動, BoundService只Activity bindService 進行啟動。
- Service中Export 和Enable兩個屬性, Export 應(yīng)用組件能不能調(diào)用被Service, Enable: 表示Service能不能被實例化。
- 重寫onBind ,onCreate,onStartCommand,onDestory 這個四個方法。
- 在調(diào)用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);
//設(shè)置全屏顯示
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ImageButton btn_play = (ImageButton) findViewById(R.id.btn_play);//獲取“播放/停止”按鈕
//啟動服務(wù)與停止服務(wù),實現(xiàn)播放背景音樂與停止播放背景音樂
btn_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (MusicService.isPlay == false) { //判斷音樂播放的狀態(tài)
startService(new Intent(MainActivity.this, MusicService.class)); //啟動服務(wù),從而實現(xiàn)播放背景音樂
//更換播放背景音樂圖標
((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.play, null));
} else {
stopService(new Intent(MainActivity.this, MusicService.class)); //停止服務(wù),從而實現(xiàn)停止播放背景音樂
//更換停止背景音樂圖標
((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.stop, null));
}
}
});
}
@Override
protected void onStart() { //實現(xiàn)進入界面時,啟動背景音樂服務(wù)
startService(new Intent(MainActivity.this, MusicService.class)); //啟動服務(wù),從而實現(xiàn)播放背景音樂
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) {
// 判斷播放狀態(tài)
if(player.isPlaying()) {
player.start();
isPlay = player.isPlaying();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
// 創(chuàng)建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 后不允許在后臺創(chuàng)建Service 上面有問題 需要調(diào)整
BindService
- Service對象中 創(chuàng)建一個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};
// 創(chuàng)建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類中的隨機數(shù)數(shù)組
for (int i = 0; i < number.size(); i++) { //遍歷數(shù)組并顯示
TextView tv = (TextView) findViewById(tvid[i]); //獲取文本框組件對象
String strNumber = number.get(i).toString(); //將獲取的號碼轉(zhuǎn)為String類型
tv.setText(strNumber); //顯示生成的隨機號碼
}
}
});
}
@Override
protected void onStart() { //設(shè)置啟動Activity時與后臺Service進行綁定
super.onStart();
Intent intent = new Intent(this, BinderService.class); //創(chuàng)建啟動Service的Intent
bindService(intent, serviceConnection, BIND_AUTO_CREATE); //綁定指定Service
}
@Override
protected void onStop() { //設(shè)置關(guān)閉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() {
}
// 創(chuàng)建MyBinder 內(nèi)部類
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() { //創(chuàng)建獲取隨機號碼的方法
List resArr = new ArrayList(); //創(chuàng)建ArrayList數(shù)組
String strNumber="";
for (int i = 0; i < 7; i++) { //將隨機獲取的數(shù)字轉(zhuǎn)換為字符串添加到ArrayList數(shù)組中
int number = new Random().nextInt(33) + 1;
//把生成的隨機數(shù)格式化為兩位的字符串
if (number<10) { //在數(shù)字1~9前加0
strNumber = "0" + String.valueOf(number);
} else {
strNumber=String.valueOf(number);
}
resArr.add(strNumber);
}
return resArr; //將數(shù)組返回
}
@Override
public void onDestroy() { //銷毀該Service
super.onDestroy();
}
}
IntentService
IntentService VS 普通Service區(qū)別:
- 在普通service進行IO請求或者是 HTTP耗時請求,會讓Android在此等待,所以使用 IntentService 解決 耗時嚴重的 HTTP請求。
- 普通的Service 不能自動開啟線程 和 自動停止服務(wù)
- 所以IntentService 解決普通Service 這兩個問題
原文鏈接:https://blog.csdn.net/qq_27217017/article/details/107426237
相關(guān)推薦
- 2022-11-17 Android開發(fā)Flutter?桌面應(yīng)用窗口化實戰(zhàn)示例_Android
- 2022-04-04 react Ant Design 實現(xiàn)menu導航菜單
- 2022-07-01 C++中strlen函數(shù)的三種實現(xiàn)方法_C 語言
- 2023-06-13 Python的加密模塊之hashlib?與?base64詳解及常用加密方法_python
- 2022-05-06 python?selenium中Excel數(shù)據(jù)維護指南_python
- 2022-11-30 jquery中在頁面加載完成后執(zhí)行某個方法_jquery
- 2022-05-22 C#單例模式與多線程用法介紹_C#教程
- 2023-04-03 python中super().__init__()作用詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支