Service

1.Service 前台服务与Notification

我们在用很多应用的时候,发现他们启动的时候,会在通知栏生成一个和该App的通知,来继续执行Service,比如墨迹天气,很多音乐App.这种叫前台服务,其实这种Service有一个很好的一点,就是不会因为Service自身的优先级低,而被系统KILL,而前台服务就不会。
前台服务的写法很容易,只需要在onCreate()中,建立一个通知,然后用startForeground()设置为前台服务即可。
下面直接放出代码,结合代码注释看看就好了,关于通知更多的内容可以看看
这里只列出Service的onCreate()部分代码

@Override
    public void onCreate() {
        super.onCreate();
        //设定一个PendingIntent,来表示点击通知栏时跳转到哪里
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        Notification.Builder builder = new Notification.Builder(this);
        //建立一个notificationManager来管理通知的出现
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //构造通知的样式,包括图片,标题,内容,时间。
        builder.setSmallIcon(R.mipmap.ic_launcher).
                setWhen(System.currentTimeMillis()).
                setContentTitle("我是标题").
                setContentText("我是内容").
                setTicker("在启动时弹出一个消息").//这个Android5.0以上可能会失效
                setWhen(System.currentTimeMillis()).
                setContentIntent(contentIntent);
                //最后通过build建立好通知
        Notification notification = builder.build();
        //通过manager来显示通知,这个1为notification的id
        notificationManager.notify(1,notification);
        //启动为前台服务,这个1为notification的id
        startForeground(1,notification);
    }

2.后台定时服务

后台定时服务其实并不是特殊的Service,只是Service的常见的一种应用,放到后台做定时更新,轮询等。这次的Service要配合Alarm以及简单的广播机制来实现。
步骤主要如下:

第一步 获得Service

AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

第二步 通过set方法设置定时任务

int time = 1000;
        long triggerAtTime = SystemClock.elapsedRealtime() + time;
        Intent i = new Intent(this,AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);

第三步 定义一个Service,在onStartCommand中开辟一个事务线程,用于处理一些定时逻辑

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
               //执行想做的操作,比如输出时间
            }
        }).start();
          //步骤二里面的代码
        return super.onStartCommand(intent, flags, startId);
    }

第四步 定义一个Broadcast,用于启动Service

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context,LongRunningService.class);
        context.startService(i);
    }
}

  

  

  

原文地址:https://www.cnblogs.com/ganchuanpu/p/5982584.html