简体   繁体   English

正在启动服务,但未调用OnCreate或OnStart

[英]Service is being started but OnCreate or OnStart are not being called

I am currently working on an android project and I am trying to start a service and when the service has started running some code to initialise some stuff. 我目前正在开发一个Android项目,我正在尝试启动一项服务,当服务开始运行一些代码来初始化一些东西时。

Below is the code I am using for the service. 以下是我用于服务的代码。

Context context;
    PowerManager.WakeLock wakeLock;

    public PowerDetectionService(Context context)
    {
        this.context = context;
    }

    public PowerDetectionService()
    {}

    public void onCreate()
    {
        super.onCreate();
        PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
    }

    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    public void receivedPowerConnected()
    {
        try
        {
            Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();
            wakeLock.acquire();
        }
        catch (Exception ex)
        {
            Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
        }
    }

    public void receivedPowerDisconnected()
    {
        try
        {
            Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
            wakeLock.release();
        }
        catch (Exception ex)
        {
            Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
        }
    }

The wake lock is always null as that bit of code never gets executed in the oncreate or onstart. 唤醒锁始终为null,因为该位代码永远不会在oncreate或onstart中执行。 I've tried putting it in the bind function but still no joy. 我已经尝试将它放入绑定功能但仍然没有快乐。

When I go into the android settings I can see that my app has the service running but I need that code to be initialised before anything would work. 当我进入android设置时,我可以看到我的应用程序已运行服务,但我需要在任何工作之前初始化该代码。

Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。

UPDATE I've discovered that the functions are being called thanks to the previous comment. 更新我发现由于之前的评论,函数被调用。 For some reason the debugger doesn't get fired. 出于某种原因,调试器不会被触发。

Below is the code that shows how to create the server as requested. 下面是显示如何根据请求创建服务器的代码。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(this);
}

public void onResume()
{
    super.onResume();
    startService(this);
}

private void startService(Context context)
{
    Intent service = new Intent(context, PowerDetectionService.class);
    context.startService(service);
}

UPDATE 2 As requested below is all the code that starts the service and performs the wake lock. 更新2如下所述,是启动服务并执行唤醒锁定的所有代码。

Below is the main activity that starts the service 以下是启动服务的主要活动

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StartPowerService(this);
        //getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    public void onResume()
    {
        super.onResume();
        StartPowerService(this);
    }

    private void StartPowerService(Context context)
    {
        Intent service = new Intent(context, PowerDetectionService.class);
        startService(service);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //case android.R.id.home:
            //    NavUtils.navigateUpFromSameTask(this);
            //    return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

Below is the class for the service 以下是该服务的类

public class PowerDetectionService extends Service {

    Context context;
    PowerManager.WakeLock wakeLock;

    public PowerDetectionService(Context context)
    {
        this.context = context;
    }

    public PowerDetectionService()
    {}

    public void onCreate()
    {
        super.onCreate();
        Log.d("SERVICE", "ON CREATE CALLED");
        PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
    }

    public int OnStartCommand(Intent intent, int flags, int startId)
    {
        Log.d("SERVICE", "ONSTARTCOMMAND Called");
        PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
        return START_STICKY;
    }

    public void onStart(Intent intent, int startId)
    {
        super.onStart(intent, startId);
        Log.d("SERVICE", "ON START CALLED");
        PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    public void receivedPowerConnected()
    {
        try
        {
            Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();
            wakeLock.acquire();
        }
        catch (Exception ex)
        {
            Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
        }
    }

    public void receivedPowerDisconnected()
    {
        try
        {
            Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
            wakeLock.release();
        }
        catch (Exception ex)
        {
            Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
        }
    }
}

And below is the mainfest file. 以下是mainfest文件。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.BoardiesITSolutions.ScreeenStay"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="PowerDetectionService"
            android:process=":ScreenStay"
            android:icon="@drawable/ic_launcher"
            android:label="Screen Stay">
        </service>
        <receiver android:name="BroadcastReceiveDetection">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

Hope this helps. 希望这可以帮助。

You are starting service in different process. 您正在以不同的流程开始服务。

    <service android:name="PowerDetectionService"
        android:process=":ScreenStay"
        android:icon="@drawable/ic_launcher"
        android:label="Screen Stay">

The debugger is attached to your main process. 调试器附加到主进程。 When the new one starts, it has no debugger attached, so it will ignore your breakpoints. 当新的启动时,它没有附加调试器,因此它将忽略您的断点。 If you want to debug remote process, you can do it via Eclipse in DDMS perspective. 如果要调试远程进程,可以通过Eclipse在DDMS透视图中进行调试。 Under devices, you can see its processes. 在设备下,您可以看到其进程。 Then you can select one and press debug selected process (green bug icon). 然后您可以选择一个并按下调试选定的进程(绿色错误图标)。 This is also useful when you only want to start debugging your app at some point. 当您只想在某个时刻开始调试应用程序时,这也很有用。

As for debugging onCreate() , you have to attach debugger after the process started, but before onCreate() is called. 至于调试onCreate() ,你必须在进程启动后附加调试器,但是在调用onCreate()之前。 You can for example put some Thread.sleep() in the beginning of onCreate() for few seconds so you can attach debugger. 例如,您可以在onCreate()的开头放置一些Thread.sleep()几秒钟,以便附加调试器。

Which class are you extending? 你在哪个班级延伸? Service? 服务?

The method onStart() is only used for old Android versions (<2.0). onStart()方法仅用于旧的Android版本(<2.0)。 For more recent versions you should use onStartCommand() as bellow: 对于更新的版本,您应该使用onStartCommand() ,如下所示:

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

And you need to return START_STICKY from the method above if you want the service to keeps running after executing the code. 如果希望服务在执行代码后继续运行,则需要从上面的方法返回START_STICKY If service is not kept alive the PowerManager.FULL_WAKE_LOCK will be released. 如果服务未保持活动,将释放PowerManager.FULL_WAKE_LOCK Probably you can also get away making wakeLock static. 也许你也可以让wakeLock静止。

To start service use: 开始使用服务:

    Intent i=new Intent(this, PowerDetectionService.class);
    startService(i);

--EDITED-- --EDITED--

As per the topic here: getApplication() vs. getApplicationContext() you may get different Context object when getting the context using getApplicationContext() . 根据这里的主题: getApplication()与getApplicationContext()在使用getApplicationContext()获取上下文时可能会得到不同的Context对象。 Try change the following line: 尝试更改以下行:

    PowerManager pm = (PowerManager)getApplication().getApplicationContext().getSystemService(Context.POWER_SERVICE);

by: 通过:

    PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);

regrads. regrads。

Just a note : 请注意:

onStart() method is deprecated, and you should use onStartCommand() instead (which will be called only if you start your service with Context.startService() . 不推荐使用onStart()方法,而应该使用onStartCommand() (只有在使用Context.startService()启动服务时才会调用它Context.startService()

However, onCreate() should called if your service does run (but only once). 但是,如果您的服务确实运行(但只运行一次),则应调用onCreate() )。

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

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