android 中 service 浅解


service中方法运行顺序? 在startService运行后 service在没有运行过的情况下,先运行onCreate 然后 运行 onStartCommand,在已经运行过的情况下,只会运行onStartCommand中的代码。 service中如何结束一个线程? 尽可能采用温和的方式来结束线程,声明一个布尔类型的变量,在service运行时,变量设为真,然后每次线程循环都询问变量,在结束线程时,将布尔值改为假,线程自然退出。 service中启动一个通知?
private void getNotification() {
Intent intent = new Intent(this, MainActivity.class);//点击之后进入MainActivity
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)//设置小图标
                .setTicker("运行中")//设置文字
                .setContentText("运行中")
                .setWhen(System.currentTimeMillis())//通知的时间
                .setAutoCancel(false)//点击后消失
                .setContentIntent(pendingIntent);//设置意图
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1, notificationBuilder.build());//显示通知
    }
service防杀? 1.对于Service被系统回收,一般做法是通过提高优先级可以解决,在AndroidManifest.xml文件中对于intent-filter可以通过android:priority = “1000”这个属性设置最高优先级,1000是最高值,如果数字越小则优先级越低。 2.我们可以用 setForeground(true) 来设置 Service 的优先级。