简体   繁体   English

服务中的onCreate()从未调用

[英]onCreate() in service never called

I want to implement a service that handle screen on/off. 我想实现一个处理屏幕开/关的服务。 To do so, I have created BootReceiver that is called at boot completed and within I start my service. 为此,我创建了BootReceiver ,该启动在启动完成后以及在启动服务时被调用。

However, OnCreate is never called, why?. 但是,从不调用OnCreate ,为什么?

When I print the log of the program I never see the onCreate 's log even though I see the onStartCommand 's log. 当我打印程序的日志时,即使看到onStartCommand的日志,也永远看不到onCreate的日志。 How is this possible? 这怎么可能? Please help me to understand this. 请帮助我理解这一点。

This is BootReceiver that is called in the very beginning: 这是一开始就调用的BootReceiver

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.w("TAG", "BootReceiver");

        Intent service = new Intent(context, ScreenListenerService.class);
            context.startService(service);

    }

}

This is the service: 这是服务:

public class ScreenListenerService extends Service {


    public void OnCreate(){
        super.onCreate();
        Log.w("TAG", "ScreenListenerService---OnCreate ");
    }


     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {

            Log.w("TAG", "ScreenListenerService---onStart ");


        }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

And the manifest: 和清单:

<service android:name=".ScreenListenerService"></service>

        <receiver android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                 <action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />
            </intent-filter>
        </receiver>

Change: 更改:

public void OnCreate(){
    super.onCreate();
    Log.w("TAG", "ScreenListenerService---OnCreate ");
}

to: 至:

public void onCreate(){
    super.onCreate();
    Log.w("TAG", "ScreenListenerService---OnCreate ");
}

Java is case sensitive, so OnCreate() != onCreate() Java区分大小写,因此OnCreate() != onCreate()

wrong spelling in onCreate . onCreate拼写错误。 You are using OnCreate instead of onCreate . 您正在使用OnCreate而不是onCreate To get rid of this kind of mistake it is better to use @override annotation everytime you override a method 要摆脱这种错误,最好在每次重写方法时都使用@override注解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM