Android IntentService in foreground



嗨,我在将IntentService作为前台服务启动时遇到问题。不幸的是,官方教程并没有告诉我太多,因为有些方法不存在,有些方法被弃用,而且没有说明它们提供的代码应该放在哪里。

我创建了自己的IntentService,并覆盖了onCreate方法。它看起来如下:

@Override
public void onCreate(){
    super.onCreate();
    Intent notificationIntent = new Intent(this, Settings.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
     Notification notification = new Notification.Builder(this)
             .setContentTitle(getText(R.string.serviceName))
             .setContentText(getText(R.string.serviceDescription))
             .setSmallIcon(R.mipmap.ic_launcher)
             .setOngoing(true)
             .setContentIntent(pendingIntent)
             .build();
    startForeground(101, notification);

我知道它不是调试站点,但肯定有一些明显的东西,我错过了。Settings类是我的Activity类,从中调用了startService,我还将所有需要的东西设置为通知,并用非零的第一个参数调用了startForeground。仍然没有通知出现,尽管我很确定,该服务正在后台工作。

如果有任何帮助,我们将不胜感激(顺便说一句,我已经在前台搜索了SO woth服务的不同主题,但没有任何帮助。)

如果使用Service而不是IntentService,则可以将您编写的代码用于构建通知&onStartCommand:中的startForeground()

public class SettingsService extends Service {
    private final IBinder mBinder = new LocalBinder();
    public class LocalBinder extends Binder {
        public SettingsService getService() {
            return SettingsService.this;
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)           {
        Intent notificationIntent = new Intent(this, SettingsService.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification notification = new Notification.Builder(this)
                .setContentTitle("myService")
                .setContentText("this is an example")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setOngoing(true)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(101, notification);
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}

此外,在onStartCommand中,如果您不希望在服务被终止时重新创建服务,则返回START_NOT_STICKY,否则返回START_STICKY

最新更新