服务中的onCreate()从未被调用过

时间:2013-04-28 16:56:46

标签: android android-service

我想实现一个处理屏幕开/关的服务。为此,我创建了BootReceiver,它在启动时被调用,并在我开始服务之内。

但是,OnCreate从未被调用,为什么?

当我打印程序日志时,即使看到onCreate的日志,我也看不到onStartCommand的日志。这怎么可能?请帮我理解这个。

这是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);

    }

}

这是服务:

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

}

清单:

<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>

2 个答案:

答案 0 :(得分:6)

变化:

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

为:

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

Java区分大小写,因此OnCreate()!= onCreate()

答案 1 :(得分:0)

onCreate中的拼写错误。您正在使用OnCreate而不是onCreate。为了摆脱这种错误,每次覆盖方法时最好使用@override注释