MainActivity.java
package cn.itcast.service;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inti();//调用init()方法
}
//inti()方法,在该方法中获取界面控件并实现控件的点击事件。
private void inti() {
Button btn_start = findViewById(R.id.btn_start);
Button btn_stop = findViewById(R.id.btn_stop);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//开启服务
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//关闭服务
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
}
MyService.java
package cn.itcast.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
//重写Service生命周期中的onCreate()方法
@Override
public void onCreate(){
super.onCreate();
Log.i("Myservice","创建服务,执行onCreate()方法");
}
//重写Service生命周期中的onStartCommand()方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Myservice","开启服务,执行onStartCommand()方法");
return super.onStartCommand(intent,flags,startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
//重写Service生命周期中的onStartCommand()方法
@Override
public void onDestroy() {
Log.i("Myservice","关闭服务,执行onDestroy()方法");
}
}
效果展示:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)