table of Contents
Words written in the front
1. The content is referenced from the Internet.
2. If there is something wrong with the content, I hope to point out or add it.
3. Task practice.
1. Step display
(1) Preparation
① Overall requirements:
1. Design the start service interface, click the button to start the service, the service execution takes 10 seconds, and the broadcast is sent to the front end.
2. When the download is complete, send a broadcast to the main interface, and a pop-up window will pop up, prompting: the download is complete.
② Document preparation:
③ List document:
(Two) code
1. Layout
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. Broadcast
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. Service
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. Active window
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;
}
}
2. Results display
The operation effect is as follows.
Three, supplement
How does Android perform time-consuming operations in Service