【发布时间】:2015-10-07 15:24:37
【问题描述】:
我正在尝试创建一项服务,该服务完全独立于活动并始终在后台运行以发送有关传入事件的通知。我通过在 onStartCommand 中返回 START_STICKY 值解决了服务终止和活动的问题。它工作得很好,但是我在发送通知时遇到了问题。问题出在 setSmallIcon 方法中。当我将对 R.drawable.ic_launcher 的引用传递到那里时,我得到了错误,上面写着那个图标 == 0。有什么办法让它正常工作吗?
这是我的 NotificationService.java
public class NotificationService extends IntentService {
private static final int UPDATE_TIME = 60 * 1000;
private ArrayList<Group> groups;
public NotificationService() {
super("NotficationService");
// TODO Auto-generated constructor stub
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
private void showNotification(String name, int remindTime) {
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification n = new Notification.Builder(this)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setContentIntent(pIntent)
.setSmallIcon(android.R.drawable.ic_delete)
.setSound(sound)
.setAutoCancel(true)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
@Override
protected void onHandleIntent(Intent intent) {
while(true) {
checkForNotification();
try {
Thread.sleep(UPDATE_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
【问题讨论】:
-
我认为您以错误的方式看待服务。 Intent Service 仅适用于特殊情况,例如如果有工作要做,然后当没有工作时它会自行退出。该文档说您不应该实现 OnStartCommand (developer.android.com/reference/android/app/…, int, int) )。您必须在 Service 类中进行扩展才能执行长时间运行的工作。
-
我不会在 Android 中使用 while(true)。它将杀死无限循环和递归线程。我认为你真正想要的是一个重复的警报,它在这个 UPDATE_TIME 间隔向你的服务发送一个意图。此外,虽然意图服务的生命周期很长,但它的 onHandleIntent() 应该很短。它旨在重用服务的 onCreate() 中的对象
标签: java android notifications alarm