在活动中启动前台服务

way*_*way 5 java eclipse oop notifications android

如何在Activity中启动服务?

我试着打电话:

Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.app_name),System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.app_name),getText(R.string.app_name), pendingIntent);
    startForeground(1, notification);
Run Code Online (Sandbox Code Playgroud)

但是,它"无法解析方法'startforeground(int,android.app.Notification)'"

如何调用startForeground?我试过getApplicationContext()无济于事.

Com*_*are 9

如何在Activity中启动服务?

打电话startService().

但是,它"无法解析方法'startforeground(int,android.app.Notification)'"

startForeground()是一种方法Service.您Service需要自己调用startForegrond()(例如,在服务中onCreate()).