Android中service的使用,前台服务

前台服务和普通服务的最大区别在于,它会一直有一个正在运行的图标在系统的状态栏
显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。比如墨迹天气

,它的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息。

我写了一个例子,效果图:


项目核心代码:

在MyService

public class MyService extends Service {


/**
* 服务第一次创建时调用
*/
@Override
public void onCreate() {
super.onCreate();
Log.i("1", "onCreate被调用了");
Notification notification = new Notification(R.drawable.ic_launcher,
"消息来了", 10000);

Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

notification.setLatestEventInfo(this, "题目", "内容", pendingIntent);

startForeground(1, notification);// 调用startForeground会让MyService变成一个前台服务,并在系统状态栏显示出来


}



/**
* 每次启动服务时调用
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("1", "onStartCommand被调用了");
// 停止服务在任何地方调用stopSelf();都可以停止
return super.onStartCommand(intent, flags, startId);
}


/**
* 服务销毁时调用
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.i("1", "onDestroy被调用了");


}


@Override
public IBinder onBind(Intent intent) {
return null;
}


}// class

如果没有明白下载我的例子

http://download.csdn.net/detail/zhaihaohao1/8291217


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值