安卓-启动前台服务

为什么要设置前台服务?

但是服务的系统 优先级还是比较低的,当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服 务。如果你希望服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收, 就可以考虑使用前台服务。前台服务和普通服务最大的区别就在于,它会一直有一个正在运 行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的 效果。当然有时候你也可能不仅仅是为了防止服务被回收掉才使用前台服务的,有些项目由于特殊的需求会要求必须使用前台服务

设置前台服务的关键API:startForeground

启动前台服务可以通过startService或bindService

下面分别演示下通过以上两种方式启动前台服务的效果。

启动前台服务后。状态栏中会显示一个小图标,下拉通知栏可以看到和提示消息一样的通知栏详情,点击可以跳转到相应的界面。

测试界面图



服务中打印了日志,大家可以参考:

通过startService时打印日志如下:

02-18 16:14:47.086 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onCreate:
02-18 16:14:47.106 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onStartCommand:

通过stopService时打印日志如下:

02-18 16:15:12.506 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onDestroy:

通过bindService时打印日志如下:

02-18 16:15:20.776 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onCreate:
02-18 16:15:20.816 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onBind: 
02-18 16:15:20.816 19659-19659/com.mobile.cdtx.blog I/ForegroundService: doSomeThingOne: 
02-18 16:15:20.816 19659-19659/com.mobile.cdtx.blog I/ForegroundService: doSomeThingTwo: 
02-18 16:15:20.816 19659-19659/com.mobile.cdtx.blog I/ForegroundService: sayEnglish:
02-18 16:15:20.816 19659-19659/com.mobile.cdtx.blog I/ForegroundService: songEnglish:

通过unbindService时打印日志如下:

02-18 16:15:35.716 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onUnbind: 
02-18 16:15:35.716 19659-19659/com.mobile.cdtx.blog I/ForegroundService: onDestroy:

测试代码如下:

主布局文件activity_foreground.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/activity_foreground"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/id_btn_start"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="启动前台服务startService"/>
    <Button
        android:id="@+id/id_btn_stop"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="结束前台服务stopService"/>
    <Button
        android:id="@+id/id_btn_bind"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="绑定前台服务bindService"/>
    <Button
        android:id="@+id/id_btn_unbind"
        android:textAllCaps="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="解绑前台服务unbindService"/>

</LinearLayout>

主界面代码如下:

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.mobile.cdtx.blog.R;
import com.mobile.cdtx.blog.main.service.ForegroundService;


public class ForegroundActivity extends AppCompatActivity implements View.OnClickListener{
    Button btnStart,btnStop,btnBind,btnUnbind;
    ForegroundService foregroundService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_foreground);

        initView();//控件的初始化
    }

    //控件的初始化
    private void initView(){
        btnStart = (Button)findViewById(R.id.id_btn_start);
        btnStart.setOnClickListener(this);
        btnStop = (Button)findViewById(R.id.id_btn_stop);
        btnStop.setOnClickListener(this);
        btnBind = (Button)findViewById(R.id.id_btn_bind);
        btnBind.setOnClickListener(this);
        btnUnbind = (Button)findViewById(R.id.id_btn_unbind);
        btnUnbind.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.id_btn_start:
                startForeground();
                break;
            case R.id.id_btn_stop:
                stopForeground();
                break;
            case R.id.id_btn_bind:
                bindForeground();
                break;
            case R.id.id_btn_unbind:
                unbindForeground();
                break;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            ForegroundService.LocalBinder binder = (ForegroundService.LocalBinder) service;
            foregroundService = binder.getService();
            //调用服务中的方法
            foregroundService.doSomeThingOne();
            foregroundService.doSomeThingTwo();
            foregroundService.sayEnglish();
            foregroundService.songEnglish();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {

        }
    };

    //启动前台服务
    private void startForeground(){
        Intent intent = new Intent(ForegroundActivity.this,ForegroundService.class);
        startService(intent);
    }
    //结束前台服务
    private void stopForeground(){
        Intent intent = new Intent(ForegroundActivity.this,ForegroundService.class);
        stopService(intent);
    }

    //绑定前台服务
    private void bindForeground(){
        Intent intent = new Intent(this, ForegroundService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }
    //解绑前台服务
    private void unbindForeground(){
        unbindService(mConnection);
    }

}

服务代码如下:

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import com.mobile.cdtx.blog.R;
import com.mobile.cdtx.blog.main.activity.JumpActivity;

public class ForegroundService extends Service {
    private static final String TAG = "ForegroundService";
    public ForegroundService() {
    }
    private LocalBinder mBinder = new LocalBinder();

    public class LocalBinder extends Binder {

        public ForegroundService getService(){
            return ForegroundService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate:");
        Intent intent = new Intent(this, JumpActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("标题")
                .setContentText("内容")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .build();
        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand:");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy:");
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind: ");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "onUnbind: ");
        return super.onUnbind(intent);
    }

    //做事情one
    public void doSomeThingOne(){
        Log.i(TAG, "doSomeThingOne: ");
    }

    //做事情two
    public void doSomeThingTwo(){
        Log.i(TAG, "doSomeThingTwo: ");
    }

    //说英文
    public void sayEnglish() {
        Log.i(TAG, "sayEnglish:");
    }
    //唱英文歌
    public void songEnglish() {
        Log.i(TAG, "songEnglish:");
    }
}
跳转界面的布局文件如下:

activity_jump.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_jump"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mobile.cdtx.blog.main.activity.JumpActivity">
    <TextView
        android:gravity="center"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="模拟跳转后的界面"/>
</RelativeLayout>

跳转界面代码如下:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.mobile.cdtx.blog.R;

public class JumpActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jump);
    }
}

最后不要忘记activity和服务均要在AndroidManifest.xml文件中注册。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值