2. doInBackground(Params...)
1. 这个方法中所有代码都会在子线程运行
2. 应该在这个方法中处理耗时任务
3. 这个方法不能进行UI操作(更新ui)
3. onProgressUpdate(Progress...)
1. 调用publishProgress(Progress...)方法后,onProgressUpdate(Progress...)方法很快就被调用
2. 这个方法可以对UI更新
4. onPostExecute(Result)
1. 任务执行完毕后并通过return返回的时候调用
2. 比如关闭进度条对话框
2. onStartCommand()
1. 启动服务时调用
3. onDestory()
1. 销毁服务时调用
4. startService() 和stopService() 都是定义在Context类中,在活动中直接调用这两个方法
5. 在service中的任一个位置调用stopSelf()方法,服务停止
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
String CHANNEL_ID = “channel_id_01”;
String CHANNEL_NAME = “channel_name_test”;
int NOTIFICATION_ID = 1;
NotificationChannel notificationChannel;
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
} else {
notification = new Notification.Builder(this)
.setContentTitle("This is content title")
.setContentText("This is content text")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.build();
}
startForeground(1, notification);
}