新建MyService继承Service(new Service)
public class MyService extends Service {
private DownloadBinder mBlinder = new DownloadBinder();
//构建内部类DownloadBinder继承Binder,
class DownloadBinder extends Binder{
//以下逻辑为与之绑定的activity可操控的逻辑
public void startDownload(){
Log.d("DownLoadBinder", "startDownload");
}
public void getProgress(){
Log.d("DownLoadBinder", "getProgress");
}
}
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBlinder; //返回DownloadBinder 对象
}
@Override
//创建时调用
public void onCreate() {
super.onCreate();
Log.d("Myservice", "start myservice");
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification notification = new NotificationCompat.Builder(this,"default")
.setContentTitle("this is title")
.setContentText("this is content text")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
@Override
//打开时调用
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Myservice", "startCommand myservice");
return super.onStartCommand(intent, flags, startId);
}
@Override
//结束时调用
public void onDestroy() {
super.onDestroy();
Log.d("Myservice", "close myservice");
}
}
活动中利用ServiceConnection 建立连接
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MyService.DownloadBinder downloadBinder;
//创建ServiceConnection匿名类
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder)service;
downloadBinder.startDownload();
downloadBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = findViewById(R.id.start);
Button close = findViewById(R.id.close);
Button bind = findViewById(R.id.bind_service);
Button unbind = findViewById(R.id.unbind_service);
start.setOnClickListener(this);
close.setOnClickListener(this);
bind.setOnClickListener(this);
unbind.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start:
Intent startIntent = new Intent(this,MyService.class);
startService(startIntent); //启动服务
break;
case R.id.close:
Intent closeIntent = new Intent(this,MyService.class);
stopService(closeIntent); //停止服务
break;
case R.id.bind_service:
Intent bindIntent = new Intent(this,MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE); //利用context的bindService方法传入相关参数,将服务与活动绑定
break;
case R.id.unbind_service:
unbindService(connection); //解绑
default:
break;
}
}
}
需要注意的是,当服务和活动绑定时,需要调用stopService和unbindService服务才会停止(两个方法调用的顺序并没有要求)