目錄
- 寫在前面的話
- 一、步驟展示
- (一)準備
- (二)代碼
- 二、結果展示
- 三、補充
寫在前面的話
1、內容參考自網路,
2、內容如果有不對的,希望可以指出或補充,
3、任務練習,
一、步驟展示
(一)準備
① 總體要求:
1、設計啟動服務界面,點擊按鈕啟動服務,服務執行耗時操作10秒,發送廣播給前端,
2、當下載完成時,發送廣播到主界面,彈出彈窗,提示:下載完成,
② 檔案準備:

③ 清單檔案:

(二)代碼
1、布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@mipmap/bg">
<Button
android:id="@+id/start_service_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#50ffffff"
android:text="開啟服務"
android:textSize="20sp"/>
<Button
android:id="@+id/stop_service_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#50ffffff"
android:text="關閉服務"
android:textSize="20sp"/>
<Button
android:id="@+id/service_state_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#50ffffff"
android:text="SERVICE狀態"
android:textSize="20sp"/>
</LinearLayout>
dialog_download.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="200dp"
android:orientation="vertical">
<!--頭部部分-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:background="#145897">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="提示"
android:textSize="20sp"
android:textColor="@color/white"/>
</LinearLayout>
<!--內容提示部分-->
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="資源下載完成"
android:textSize="20sp"
android:textColor="@color/black"
android:gravity="center"
android:background="@color/white"/>
<!--按鈕部分-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#e8e8e8"
android:gravity="center">
<Button
android:id="@+id/dialog_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="確定"
android:textSize="15sp"
android:backgroundTint="#fd8638"/>
</LinearLayout>
</LinearLayout>
2、廣播
MyReceiver.java
package com.example.lian;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
private Button btn;
@Override
public void onReceive(Context context, Intent intent) {
// 獲得廣播發送的資料
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_download,null,false);
dialogBuilder.setView(view);//設定好了的對話框
AlertDialog alertDialog = dialogBuilder.create();
//按鈕的實作
btn = view.findViewById(R.id.dialog_btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context,"確認成功!",Toast.LENGTH_SHORT).show();
alertDialog.dismiss();//關閉對話框
}
});
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
}
3、服務
MyService.java
package com.example.lian;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.view.WindowManager;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//下載對話框
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getApplicationContext());
dialogBuilder.setMessage("是否要下載資源");
dialogBuilder.setNegativeButton("否", null);
dialogBuilder.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//進度對話框
ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());
progressDialog.setMessage("請耐心等待10秒...");
//在show()之前,要先設定Dialog的型別為TYPE_SYSTEM_ALERT才能正常彈出對話框
progressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//必有
progressDialog.show();
//關閉操作
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);//顯示10秒
} catch (InterruptedException e) {
e.printStackTrace();
}
progressDialog.dismiss();//關閉ProgressDialog
}
});
thread.start();
//監聽對話框是否已經關閉,關閉后彈出↓
progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
//發送廣播
Intent intent = new Intent(MyService.this,MyReceiver.class);
sendBroadcast(intent);
}
});
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this,"關閉服務成功",Toast.LENGTH_SHORT).show();
}
}
4、活動視窗
MainActivity.java
package com.example.lian;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mStartBtn, mStopBtn, mStateBtn;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取控制元件
mStartBtn = findViewById(R.id.start_service_btn);
mStopBtn = findViewById(R.id.stop_service_btn);
mStateBtn = findViewById(R.id.service_state_btn);
//添加監聽器
mStartBtn.setOnClickListener(this);
mStopBtn.setOnClickListener(this);
mStateBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service_btn:
intent = new Intent(this, MyService.class);
startService(intent);
break;
case R.id.stop_service_btn:
intent = new Intent(this, MyService.class);
stopService(intent);
break;
case R.id.service_state_btn:
boolean serviceRun = isServiceRun(this,"com.example.lian.MyService");
if(serviceRun == true){
Toast.makeText(this,"服務正在運行",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"服務已關閉",Toast.LENGTH_SHORT).show();
}
break;
}
}
//判斷服務(com.example.lian.MyService)是否正在運行
public boolean isServiceRun(Context context, String servicename) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//獲取正在運行的服務,引數:表示最多回傳的數量
List<ActivityManager.RunningServiceInfo> lists = activityManager.getRunningServices(40);
//
for(ActivityManager.RunningServiceInfo list: lists){
//獲取正在運行的服務名稱并判斷
if(servicename.equals(list.service.getClassName())){
return true;
}
}
return false;
}
}
二、結果展示
運行效果如下,

三、補充
Android如何在Service中執行耗時操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/252703.html
標籤:其他
上一篇:Android學習記錄(十六)
