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

android 后台服务、通知信息

2016-08-03 20:07 507 查看
IntentService 也是 Context,需要在 Manifest 配置中添加<service android:name=".abcservice"/>

创建 abcService extends IntentService,重载 onHandleIntent 后就可以用 startService(Intent) 启动 abcService 了。

因为 Service 具有后台运行的特性,我们可以使系统不断运行它以达到检测消息等目的。在abcService 中添加方法:

public static void setServiceAlarm(Context c, boolean on){
AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(c,0,new Intent(c,abcService.class),0);
if(on){am.setRepeating(AlarmManager.RTC,System.currentTimeMillis(),1000*15,pi);}
else{am.cancel(pi);pi.cancel();}
}

public static boolean isServiceAlarmOn(Context c){
PendingIntent pi = PendingIntent.getService(c,0,new Intent(c,abcService.class),PendingIntent.FLAG_NO_CREATE);
return pi!=null;
}

将 startService 修改为 abcService.setServiceAlarm(getActivity(),true); 这样即可以15秒为间隔反复运行abcService。

分析代码:注意
PendingIntent,getService 等价于 将来 startService(Intent),getActivity 等价于将来 startActivity,同理还有 getBroadcast。

后台服务常常会发送通知给用户 ,比如收到了QQ消息。在onHandleIntent 适当处给用户发送通知:

Resources r = getResources();
PendingIntent pi = PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0);
Notification n = new NotificationCompat.Builder(this)
.setTicker(r.getString(R.string.n_title))
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(z.getString(R.string.n_title))
.setContentText(r.getString(R.string.n_text))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManager nm = (NotificationManagero)getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,n);setAutoCancel(true) 表明当用户点击此 Notification 后自动将该消息删除。注意 notify 第一个参数id 0,当再次发送通知时,相同id的通知会被替换。

参考

Notification使用以及PendingIntent.getActivity()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android