Android Api Demos学习之Notification Service Receiver 消息推广
Make Change No Back!
正在弄一个新闻客户端。需要消息推广,就是有新的内容时,在顶部状态栏那里提示用户。
首先想到的就是Notification+Service.
下面是实现代码:
public class RetriveArticleService extends Service {
private static int MOOD_NOTIFICATIONS = 1;
private Notification mN;
private NotificationManager mNm;
private Intent mI;
private PendingIntent mP;
@Override
public void onCreate() {
// TODO Auto-generated method stub
mN = new Notification();
//img
mN.icon = R.drawable.custom_app_icon;
//text
mN.tickerText = getString(R.string.notification);
//audio
mN.defaults = Notification.DEFAULT_SOUND;
//click and auto_cancel
mN.flags = Notification.FLAG_AUTO_CANCEL;
mNm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//点击顶部状态栏的消息后,welcomeactivity为需要跳转的页面
mI = new Intent(this, WelcomeActivity.class);
mP = PendingIntent.getActivity(this, 0, mI, 0);
//开启新的线程从服务器获取数据
Thread getArticlesThread = new Thread(null, mTask, "getNewArticles");
getArticlesThread.start();
super.onCreate();
}
Runnable mTask = new Runnable() {
@Override
public void run() {
//get data from service
String contentText = "brains";
showNotification(contentText);
}
};
private void showNotification(String contentText) {
mN.setLatestEventInfo(RetriveArticleService.this,
getString(R.string.notification), contentText, mP);
mNm.notify(MOOD_NOTIFICATIONS, mN);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
mNm.cancel(MOOD_NOTIFICATIONS);
super.onDestroy();
}
private final IBinder mBinder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
然后需要在xml文件里注册这个服务。
<service android:name="com.brains.userpackage.service.RetriveArticleService" android:process=":getnewArticles"></service>
注意process这属性,注册时候有两种方法,一个是以"."开头,则为此服务开启一个 全局的独立进程;一个是以":"开头,则为此服务开启一个为此应用私有的独立进程。
最后只需要启动这个服务就可以了,启动的代码为:
startService(new Intent(this, RetriveArticleService.class));
运行,就能在状态栏里面发现推送的信息了....
不过我们上面还提高了recevier.广播。
这里我主要运用了广播监听系统事件的功能,来实现开机后就能启动。
贴出广播标准ACTION常量:
广播的注册:
<receiver android:name="com.brains.userpackage.service.RetriveArticleReceive">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
我这里就是监听系统开机的完成。好多程序能够开机启动,就是这么完成的。
OK。做个记录,方便以后查阅。
标签:
Android
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架