2016-07-21 30 views
0

您好我有问题启动IntentService作为前台服务。不幸的是,官方教程并没有告诉我很多方法不存在,有些已被弃用,而且也没有说它们提供的代码的放置位置。前景中的Android 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服务不同的主题,但没有帮助。)

+0

你的用例是什么让它在前台? – apelsoczi

+0

应用程序是:你设置一些设置即。电话号码。从设置活动中,按下启动按钮,服务启动并监听一些事件,如果发生事件,服务会发出呼叫(例如,在电话发起动作时有用,但它独自留在家中)。我希望通知用户,该服务处于活动状态。您可以从设置活动中禁用服务。 – DawidPi

+0

由于一个IntentService是onHandleIntent后立即销毁()完成后,你可能不希望一个IntentService – ianhanniballake

回答

1

如果使用Service而不是IntentService,你可以把代码你写打造& startForeground()onStartCommand通知:

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); 
    } 
} 

Additionnaly,在onStartCommand,返回START_NOT_STICKY如果你不想当它被杀死否则返回重新创建服务