您的位置:首页 > 移动开发 > Android开发

android服务- Notification创建通知 - startForeground 使用前台服务

2016-01-12 15:19 731 查看
版本3.0以上,推荐使用NotificationCompat.Builder类来构建Notification。

<span style="font-family:FangSong_GB2312;">   </span><span style="font-family:Courier New;"> @Override
public void onCreate() {
super.onCreate();
long[] vibrates = {0, 1000, 1000, 1000};</span>
<span style="font-family:Courier New;">
//使用前台服务
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("This is title")
.setContentText("This is content")
.setContentIntent(pendingIntent)
.setVibrate(vibrates) //震动
.setDefaults(1);//跟随手机设置

Notification notification = mBuilder.build();

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notification);

//当一个Service被当作Foreground来运行的时候,就不会因为内存不足而被销毁
startForeground(1, notification);

Log.d("MyService", "onCreate executed");
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息