【发布时间】:2021-04-16 18:02:41
【问题描述】:
我正在通过 MainActivity 运行服务
startService(mServiceIntent)
但是只有 onCreate 方法被调用。我需要从 Intent 收集一些额外的参数,所以我想 onStartCommand 也被调用。你知道它没有发生的原因是什么吗?我的服务代码。
class ImportantService : Service() {
var phoneListener : MyPhoneStateListener? = null
var listening = false
var telephony: TelephonyManager? = null
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
override fun onCreate() {
super.onCreate()
Log.d("ImportantService", "On Create")
//startListen()
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
val builder = NotificationCompat.Builder(this, "ch1")
.setContentText("Content text")
.setContentTitle("Content title")
startForeground(101,builder.build())
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
// this method is never invoked
Log.d("ImportantService", "On Start")
if(listening)
{
Log.d("ImportantService", "Started")
startListen()
}
else
{
Log.d("ImportantService", "Stopped")
// stopListen()
}
}
fun startListen()
{
Log.d("Service", "startListen")
}
}
【问题讨论】:
-
任何好的 IDE 都应该警告您
return语句之后的代码不可访问。注意来自 IDE 的警告很有用,并且可以节省大量的故障排除时间。这是一个完美的例子。