//功能描述:
// star_btn:打开一个后台服务,并弹窗提示,一个test变量会进行自加操作,并在logcat打印出来
// stop_btn :关闭一个服务
//2023.6.23
//Liyumin
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button star_btn = findViewById(R.id.StarSevers);
Button stop_btn = findViewById(R.id.StopSevers);
//1.开始后台服务的按键
star_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
//2.关闭后台服务的按键
stop_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
}
Myservice:
public class MyService extends Service {
private static final String TAG="MyService";
private int test = 0;
private Handler handler;
private Runnable runnable;
//4.真正的后台服务程序要在这里给出 原因:现在的版本取消了onStart()方法
public MyService() {
// 这是因为在 Android 中,后台服务是运行在主线程中的,
// 而主线程主要负责处理用户界面交互和更新。如果在主线程中执行耗时操作或循环操作
// ,就会导致界面卡顿或无响应的情况。
//
// 使用句柄和Runnable的方式,可以将自增操作放在一个延迟执行的任务中,
// 并通过句柄的定时调度,将任务放置在主线程消息队列中。
// 这样,自增操作就会在主线程空闲时被执行,而不会阻塞主线程的运行。
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
test++;
Log.d(TAG, "MyService: test is " + test);
handler.postDelayed(this, 1000); // 每秒钟执行一次自增操作
}
};
handler.post(runnable); // 启动后台任务
}
//3.这里是一段初始化程序,用来提示已经进入到了service的初始化服务中来(仅执行一次)
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"打开了一个后台服务",Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable); // 停止后台任务
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}