Android服务——前台服务

      我们通常创建的服务都是运行在后台的,但是当我们遇到这样的场景的时候:一个播放音乐的音乐播放器服务应该被设置在前台运行,因为用户要明确的知道它们的操作。状态栏中的通知需要指明了当前的歌曲,并且用户启动一个跟这个音乐播放器交互的Activity。

这个时候我们需要创建前台服务。


1. 创建前台服务

  • 我们需要实现我们的服务类 
  • 需要提供一个通知栏图标,并且调用startForeground(API
         level 5 之前的需要使用setForeground())
  • 需要注册服务,在xml配置service

2. ForegroundServer.java

      1). 我们在onStartCommand函数中调用displayNotification来展示前台服务的描述

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w(TAG, "onStartCommand...");
        //设置成前台任务
        displayNotification();
        return super.onStartCommand(intent, flags, startId);
    }

      2).  displayNotification调用startForeground

    private void displayNotification()
    {
        Intent intent = new Intent(TAG);
        PendingIntent piResult0 = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Notification noti = new Notification.Builder(ForegroundServer.this)
                .setContentTitle("前台服务运行中...")
                .setContentText("点击取消")
                .setSmallIcon(android.R.drawable.btn_star)
                .setContentIntent(piResult0)
                .build();

        ForegroundServer.this.startForeground(1, noti);

        Toast.makeText(this, "开启前台服务", Toast.LENGTH_LONG).show();
    }

      3). 启动服务,我们在Activity中调用startService来启动前台服务,部分代码如下:

        final Intent intentService = new Intent(MyActivity.this, ForegroundServer.class);

        startService(intentService);

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(MyActivity.this, "关闭前台服务", Toast.LENGTH_LONG).show();
                stopService(intentService);

            }
        };

        registerReceiver(broadcastReceiver, new IntentFilter(ForegroundServer.TAG));

   当点击通知栏后,会关闭服务。


用startService来开启服务时必须用stopService来关闭服务。(也可以用bindService和unbindService来开启和关闭服务)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值