Android Service開(kāi)發(fā)應(yīng)用實(shí)例
Service 開(kāi)發(fā)應(yīng)用
在后臺(tái)長(zhǎng)時(shí)間運(yùn)行,沒(méi)有界面UI, 在后臺(tái)下載文件和獲取用戶(hù)GPS信息
- Service: 分為 startService 和 BoundService;
- 只有Activity 調(diào)用startService才會(huì)通知服務(wù)啟動(dòng), BoundService只Activity bindService 進(jìn)行啟動(dòng)。
- Service中Export 和Enable兩個(gè)屬性, Export 應(yīng)用組件能不能調(diào)用被Service, Enable: 表示Service能不能被實(shí)例化。
- 重寫(xiě)onBind ,onCreate,onStartCommand,onDestory 這個(gè)四個(gè)方法。
- 在調(diào)用Service 時(shí)候判斷本Service是否在正在運(yùn)行
// 需要在XML文件中配準(zhǔn)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);//獲取“播放/停止”按鈕 //啟動(dòng)服務(wù)與停止服務(wù),實(shí)現(xiàn)播放背景音樂(lè)與停止播放背景音樂(lè) btn_play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (MusicService.isPlay == false) { //判斷音樂(lè)播放的狀態(tài) startService(new Intent(MainActivity.this, MusicService.class)); //啟動(dòng)服務(wù),從而實(shí)現(xiàn)播放背景音樂(lè) //更換播放背景音樂(lè)圖標(biāo) ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.play, null)); } else { stopService(new Intent(MainActivity.this, MusicService.class)); //停止服務(wù),從而實(shí)現(xiàn)停止播放背景音樂(lè) //更換停止背景音樂(lè)圖標(biāo) ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.stop, null)); } } }); } @Override protected void onStart() { //實(shí)現(xiàn)進(jìn)入界面時(shí),啟動(dòng)背景音樂(lè)服務(wù) startService(new Intent(MainActivity.this, MusicService.class)); //啟動(dòng)服務(wù),從而實(shí)現(xiàn)播放背景音樂(lè) 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對(duì)象,加載播放音頻對(duì)象 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 后不允許在后臺(tái)創(chuàng)建Service 上面有問(wèn)題 需要調(diào)整
BindService
- Service對(duì)象中 創(chuàng)建一個(gè)MyBinder類(lèi)型的綁定器, 返回其綁定對(duì)象
- Activity中 ServiceConnection 重寫(xiě)其中方法,在此方法中獲取Service獨(dú)享
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 對(duì)象 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); //獲取隨機(jī)選號(hào)按鈕 btn_random.setOnClickListener(new View.OnClickListener() { //單擊按鈕,獲取隨機(jī)彩票號(hào)碼 @Override public void onClick(View v) { List number = binderService.getRandomNumber(); //獲取BinderService類(lèi)中的隨機(jī)數(shù)數(shù)組 for (int i = 0; i < number.size(); i++) { //遍歷數(shù)組并顯示 TextView tv = (TextView) findViewById(tvid[i]); //獲取文本框組件對(duì)象 String strNumber = number.get(i).toString(); //將獲取的號(hào)碼轉(zhuǎn)為String類(lèi)型 tv.setText(strNumber); //顯示生成的隨機(jī)號(hào)碼 } } }); } @Override protected void onStart() { //設(shè)置啟動(dòng)Activity時(shí)與后臺(tái)Service進(jìn)行綁定 super.onStart(); Intent intent = new Intent(this, BinderService.class); //創(chuàng)建啟動(dòng)Service的Intent bindService(intent, serviceConnection, BIND_AUTO_CREATE); //綁定指定Service } @Override protected void onStop() { //設(shè)置關(guān)閉Activity時(shí)解除與后臺(tái)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)部類(lè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)建獲取隨機(jī)號(hào)碼的方法 List resArr = new ArrayList(); //創(chuàng)建ArrayList數(shù)組 String strNumber=""; for (int i = 0; i < 7; i++) { //將隨機(jī)獲取的數(shù)字轉(zhuǎn)換為字符串添加到ArrayList數(shù)組中 int number = new Random().nextInt(33) + 1; //把生成的隨機(jī)數(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() { //銷(xiāo)毀該Service super.onDestroy(); } }
IntentService
IntentService VS 普通Service區(qū)別:
- 在普通service進(jìn)行IO請(qǐng)求或者是 HTTP耗時(shí)請(qǐng)求,會(huì)讓Android在此等待,所以使用 IntentService 解決 耗時(shí)嚴(yán)重的 HTTP請(qǐng)求。
- 普通的Service 不能自動(dòng)開(kāi)啟線程 和 自動(dòng)停止服務(wù)
- 所以IntentService 解決普通Service 這兩個(gè)問(wèn)題
到此這篇關(guān)于Android Service開(kāi)發(fā)應(yīng)用實(shí)例的文章就介紹到這了,更多相關(guān)Android Service內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
android 獲取文件的擴(kuò)展名和去掉文件擴(kuò)展名的小例子
android 獲取文件的擴(kuò)展名和去掉文件擴(kuò)展名的小例子,需要的朋友可以參考一下2013-06-06Android實(shí)現(xiàn)騰訊新聞的新聞?lì)悇e導(dǎo)航效果
這篇文章主要介紹了Android實(shí)現(xiàn)騰訊新聞的新聞?lì)悇e導(dǎo)航效果,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03詳解Android應(yīng)用main函數(shù)的調(diào)用
Android常識(shí),App主線程初始化了Looper,調(diào)用prepare的地方是ActivityThread.main函數(shù)。問(wèn)題來(lái)了,App的main函數(shù)在哪兒調(diào)用,下面我們來(lái)一起學(xué)習(xí)一下吧2019-06-06Android支付寶支付開(kāi)發(fā)實(shí)例
這篇文章主要為大家詳細(xì)介紹了Android支付寶支付開(kāi)發(fā)實(shí)例的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-04-04Android開(kāi)發(fā) Bundle傳值的理解與使用小結(jié)
這篇文章主要介紹了Android開(kāi)發(fā) Bundle傳值的理解與使用小結(jié),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-07-07Android仿微信文章懸浮窗效果的實(shí)現(xiàn)代碼
這篇文章主要介紹了Android仿微信文章懸浮窗效果的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-10-10Android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器
這篇文章主要為大家詳細(xì)介紹了Android studio實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03安卓(Android)開(kāi)發(fā)之統(tǒng)計(jì)App啟動(dòng)時(shí)間
當(dāng)大家要改善APP啟動(dòng)速度優(yōu)化的時(shí)候,首先要知道App的啟動(dòng)時(shí)間,那么改如何統(tǒng)計(jì)時(shí)間呢,下面我們一起來(lái)看看。2016-08-08Android Retrofit 中文亂碼問(wèn)題的解決辦法
這篇文章主要介紹了Android Retrofit 中文亂碼問(wèn)題的解決辦法的相關(guān)資料,希望通過(guò)本文能幫助到大家,讓大家遇到這種問(wèn)題及時(shí)的解決,需要的朋友可以參考下2017-10-10