onStartCommand 永远不会被调用
onStartCommand is never invoked
我是 运行 来自 MainActivity 的服务
startService(mServiceIntent)
但是只有 onCreate 方法 invoked.I 需要从 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")
}
}
确保将 return super.onStartCommand(intent, flags, startId)
移动到函数的末尾。
我是 运行 来自 MainActivity 的服务
startService(mServiceIntent)
但是只有 onCreate 方法 invoked.I 需要从 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")
}
}
确保将 return super.onStartCommand(intent, flags, startId)
移动到函数的末尾。