众所周知,Service是Android中实现程序后台运行的解决方案,非常适合于执行不需要和用户交互而且要求长期运行的任务。Notification是显示在手机状态栏的通知,通过Notification和startForeground可以将Service后台服务设置为前台服务。
前台Service的优先级高于后台Service。
Service是处理一些后台任务,在主线程中,并不能执行耗时操作。而Thread是开启一个子线程,在子线程中执行耗时操作,这样不会阻塞主线程。
那么Service与Thread、Process有什么关系呢?
其实它们之间并无太大关联,只是Service可以放在其他进程中,Service是进程中的,Thread也是进程中的,Service中耗时操作又可以在通过Thread执行。Service中的IBinder可以帮助我们与其他进程进行通信。
获取当前进程:Thread.currentThread().getId();
在Service中创建一个子线程与Activity中创建一个子线程有什么区别?
当Activity被销毁,就无法获取在被销毁的Activity中创建的子线程实例了。例如,Activity创建了一个子线程在后台运行,执行完之后,返回数据时,创建它的Activity已被销毁,这是线程不安全的。再例如,Activity1创建了一个子线程,Activity2是无法对Activity1创建的子线程进行操作。 而Service是一个服务,所有的Activity都可以与该Service进行关联,即使Activity被销毁,但依然可以获取Service中的IBinder的实例。 所以,用Service处理后台任务,Activity就可以放心的被finish掉了,完全不用担心对后台任务无法进行控制。
创建简单通知
以下代码段说明了一个指定某项 Activity 在用户点击通知时打开的简单通知。 请注意,该代码将创建TaskStackBuilder对象并使用它来为操作创建PendingIntent。
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有