Service绑定活动
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Service1.DownloadBinder binder;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder=(Service1.DownloadBinder) service;
binder.startDownload();
binder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.free:
Intent intent=new Intent(this,Service1.class);
bindService(intent,connection, Context.BIND_AUTO_CREATE);
break;
case R.id.bind:
unbindService(connection);
break;
}
}
}
public class Service1 extends Service {
DownloadBinder binder=new DownloadBinder();
class DownloadBinder extends Binder{
public void startDownload(){
Log.d("mes", "startDownload: ");
}
public int getProgress(){
Log.d("mes", "getProgress: ");
return 0;
}
}
@Override
public void onCreate() {
Log.d("mes", "onCreate: create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("mes", "onStartCommand: start");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
前台service
为了避免service被回收,可以采用前台service的方式,调用service的startForeground方法,传入通知id和通知对象,即可实现前台service的效果。
public void onCreate() {
Log.d("mes", "onCreate: create");
NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
//创建通知渠道,三个参数分别是,全局唯一的渠道id,用户所见渠道名称,初始渠道重要性
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel("ChannelId", "The name seen by the user", 2);
manager.createNotificationChannel(channel);
}
Notification notification=new NotificationCompat.Builder(this,"ChannelId")
.setContentTitle("This is content title")
.setContentText("This is content text")
//小图标,这是所必需的唯一用户可见内容。
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
.build();
startForeground(1,notification);
super.onCreate();
}
注意需要注册
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
IntentService
进行耗时操作的service如果放在主线程中很容易出现 应用未响应的情况,因此service中的操作应该放在子线程中进行。但是每次开启子线程后的service会一直在后台占用资源,因此在执行完毕后需要stopSelf释放资源,这样做写了许多重复的线程操作和释放资源代码。
好在Android提供了子类IntentService,每次操作会自动完成这些步骤,因此写服务的时候应该继承IntentService。