Android使用前台服务

2016-08-10  本文已影响151人  CalvinNing

Android使用前台服务和普通服务在代码上的区别也就是一个Notification,代码如下:

public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.t("MyService").i("onCreate");
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("title");
        builder.setContentText("text");
        builder.setWhen(System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pt = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pt);
        Notification notification = builder.build();
        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.t("MyService").i("onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.t("MyService").i("onDestroy");
    }
}

要从前台删除服务,需要调用stopForeground()方法,这个方法需要一个布尔型参数,指示是否删除状态栏通知。这个方法不终止服务。但是,如果你终止了正在运行的前台服务,那么通知也会被删除。


下面谈谈这期间遇到的蛋疼的事,直接上图对比:

before.gif after.gif

一开始我写完代码运行,一直是图before的效果,检查代码一遍又一遍,也没发现问题出在哪里,就在我几近崩溃的时候,想着是不是因为我没设置小图标,就试着设置了下图标,结果就ok了,之后我又复习了一下Notification的知识,原来不设置小图标Notification根本显示不出来,哎~

builder.setSmallIcon(R.mipmap.ic_launcher);

顺便附上学习Notification时参考过的好文一篇——郭神(郭霖)之《Android通知栏的微技巧》

上一篇 下一篇

猜你喜欢

热点阅读