简介
Service是Android系统中的四大组件之一,它是一种长生命周期的,没有可视化界面,运行于后台的一种服务程序。
简单来说,Service可以理解为一个没有界面的Activity。
使用
MainActivity
public class MainActivity extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
intent = new Intent(this, AliveService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Android 8.0以上调用
startForegroundService(intent);
} else {
startService(intent);
}
}
@Override
protected void onDestroy() {
stopService(intent);
super.onDestroy();
}
}
AliveService
public class AliveService extends Service {
public AliveService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//点击服务进入MainActivity
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);
//前台通知显示
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "alive_channel";//自定义字符串
String name = "测试前台服务功能";//频道名称
String description = "前台服务,可以一直运行";//通道描述,界面不显示
int importance = NotificationManager.IMPORTANCE_HIGH;//优先级
NotificationCompat.Builder notification = null;
//Android8.0之后和之前的通知有很大的差异
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id, name, importance);
channel.setDescription(description);
channel.enableLights(true);
channel.setLightColor(Color.RED);
manager.createNotificationChannel(channel);
notification = new NotificationCompat.Builder(this, id)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher_background)//图标
.setTicker("前台Service启动")
.setContentTitle("前台Service运行中")
.setContentText("这是一个正在运行的前台Service")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
} else {
notification = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher_background)
.setTicker("前台Service启动")
.setContentTitle("前台Service运行中")
.setContentText("这是一个正在运行的前台Service")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
}
startForeground(1, notification.build());
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
注意点:
1.Service既然属于Android四大组件之一,所以也是需要在清单文件【AndroidManifest.xml】中注册的
<service
android:name=".AliveService"
android:enabled="true"
android:exported="true" />
2.Service需要申请权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3.Service也是运行在主线程的,所以如果要是在Service中做耗时操作的话,尽量开启子线程进行耗时操作。
4.当第一次启动Service时,Service的onCreate方法会执行,然后执行onStartCommand方法,当Service已经存在的时候,再次调用Service的时候,会直接执行onStartCommand方法,不再执行onCreate方法。