关于android 四大组件之一Service 一直以来用的都不怎么多 ,时间一长就忘了,每次都要去查很麻烦,今天就写下了方便自己日后查阅。
android的服务依据是否需要和前天交互分为两种
- 不可交互的后台服务------------------------startService()
- 可交互的后台服务---------------------------bindService()
两种服务的区别主要在于服务的启动方式
startService()和bindService()
startService()对应的是不可交互的服务
bindService()对应的是可交互的启服务
不可交互的后台服务就是服务在后台执行我们不能获取服务中的东西
可交互的后台通过一个ServiceConnection 来获取一个Binder 对象来调用Service中的方法,从而实现与前端的交互。
/***************************************************************************************************/
android 服务的创建
创建一个类继承Service重写onBinde()方法 服务的生命周期
onCreate、onStartCommand、onDestroy这三个方法。
当我们startService()的时候,首次创建Service会回调onCreate()方法,
然后回调onStartCommand()方法,再次startService()的时候,
就只会执行一次onStartCommand()。服务一旦开启后,
我们就需要通过stopService()方法或者stopSelf()方法,就能把服务关闭,这时就会回调onDestroy() 。
服务是在UI线程中执行的因此不能在服务中执行耗时的操作,除非手动开子线程去执行耗时操作。
另外,需要注意的是即使我们手动调用stopService 服务的onDestroy()方法也执行了,但是耗时操作任然会在后台执行 除非把进程给干掉!
/***************************************************************************************************/
下面是不可交互的service 的代码
/**
* 不可交互的后台服务,
* 继承service 实现onBind()方法,Service的生命周期很简单,
* 分别为onCreate、onStartCommand、onDestroy这三个。
* /
public class UnInteractionService extends Service {
private static final String TAG = "service";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Log.e(TAG, "on create");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "on start command");
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Log.e(TAG, "执行耗时操作");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e(TAG, "on destroy");
super.onDestroy();
}
}
对应的activity代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_start_service, tv_stop_service;
private Intent unInteractionSIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initAction();
}
private void initView() {
tv_start_service = (TextView) findViewById(R.id.tv_start_service);
tv_stop_service = (TextView) findViewById(R.id.tv_stop_service);
}
private void initAction() {
tv_start_service.setOnClickListener(this);
tv_stop_service.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_start_service:
unInteractionSIntent = new Intent(this, UnInteractionService.class);
startService(unInteractionSIntent);
break;
case R.id.tv_stop_service:
stopService(unInteractionSIntent);
break;
}
}
}
可以开出来服务的生命周期都执行了,但是在onDestroy后 服务中的耗时操作还是依然在执行着。
下面是可交互的service 的代码
/**
* 可交互的后台服务是指前台页面可以调用后台服务的方法,
* 可交互的后台服务实现步骤是和不可交互的后台服务实现步骤是一样的,
* 区别在于启动的方式和获得Service的代理对象
*/
public class InteractionService extends Service {
private static final String TAG = "service";
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, "on bind");
return new MyBinder();
}
public class MyBinder extends Binder {
public void showToast() {
Log.e(TAG, "show toast");
}
}
@Override
public void onCreate() {
Log.e(TAG, "on create");
super.onCreate();
}
@Override
public void unbindService(ServiceConnection conn) {
super.unbindService(conn);
Log.e(TAG, "unbind service");
}
@Override
public void onDestroy() {
Log.e(TAG, "on destroy");
super.onDestroy();
}
}
对应的activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_bind_service, tv_unbind_service;
private Intent interactionSIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initAction();
}
private void initView() {
tv_bind_service = (TextView) findViewById(R.id.tv_bind_service);
tv_unbind_service = (TextView) findViewById(R.id.tv_unbind_service);
}
private void initAction() {
tv_bind_service.setOnClickListener(this);
tv_unbind_service.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_bind_service:
interactionSIntent = new Intent(this, InteractionService.class);
bindService(interactionSIntent, connection, BIND_AUTO_CREATE);
break;
case R.id.tv_unbind_service:
unbindService(connection);
break;
}
}
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
InteractionService.MyBinder binder = (InteractionService.MyBinder) service;
binder.showToast();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
前台服务
public class WeatherService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
showNotification();
}
private void showNotification() {
Notification.Builder notify = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getDate(System.currentTimeMillis()))
.setContentText("今日大雪");
Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notify.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = notify.build();
nm.notify(0,notification);
startForeground(0,notification);
}
@SuppressLint("SimpleDateFormat")
private String getDate(long time) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日-HH:mm:ss");
return dateFormat.format(new Date(time));
}
}
对应的activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_fore_service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initAction();
}
private void initView() {
tv_fore_service = (TextView) findViewById(R.id.tv_fore_service);
}
private void initAction() {
tv_fore_service.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_fore_service:
startService(new Intent(this, WeatherService.class));
break;
}
}
}
下面是一些获取系统的服务可能会用到的
1.判断Wifi是否开启
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
boolean enabled = wm.isWifiEnabled();
2.获取系统最大音量
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int max = am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
3.获取当前音量
AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
int current = am.getStreamMaxVolume(AudioManager.STREAM_RING);
4.判断网络是否有连接
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
etworkInfo info = cm.getActiveNetworkInfo();
boolean isAvailable = info.isAvailable();