1、内容参考自网络。
2、内容如果有不对的,希望可以指出或补充。
3、任务练习。
① 总体要求:
1、设计启动服务界面,点击按钮启动服务,服务执行耗时操作10秒,发送广播给前端。
2、当下载完成时,发送广播到主界面,弹出弹窗,提示:下载完成。
1、布局
activity_main.xml
<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
<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中执行耗时操作