服务正在被启动但OnCreate中或的OnStart不被称为 [英] Service is being started but OnCreate or OnStart are not being called

查看:291
本文介绍了服务正在被启动但OnCreate中或的OnStart不被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前工作的一个Android项目,我试图启动一个服务,当服务已经启动运行某些code初始化一些东西。

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.

下面是code我使用该服务。

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

为code的该位永远不会在OnCreate或执行的OnStart唤醒锁总是空。我试图把它绑定功能,但仍然没有喜悦。

The wake lock is always null as that bit of code never gets executed in the oncreate or onstart. I've tried putting it in the bind function but still no joy.

当我进入Android设置,我可以看到我的应用程序有服务运行,但我需要code被初始化之前,任何事情会工作。

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.

感谢您的帮助,您可以提供。

Thanks for any help you can provide.

更新
我发现该功能是被称为拜previous评论。出于某种原因,调试器不会被解雇。

UPDATE I've discovered that the functions are being called thanks to the previous comment. For some reason the debugger doesn't get fired.

下面是code,它展示了如何创建服务器的要求。

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

更新2
正如下文要求是所有code启动该服务,并执行之后锁定。

UPDATE 2 As requested below is all the code that starts the service and performs the wake lock.

下面是启动该服务的主要活动

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

}

下面是类服务

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

和下面是mainfest文件。

And below is the mainfest file.

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

推荐答案

哪个类是你延长?服务?

Which class are you extending? Service?

该方法在onStart()仅用于旧版本的Andr​​oid(小于2.0)。对于较新版本的你应该使用 onStartCommand()波纹管:

The method onStart() is only used for old Android versions (<2.0). For more recent versions you should use onStartCommand() as bellow:

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

和您需要从,如果你希望服务一直执行code运行后,上述方法返回 START_STICKY 。如果服务没有更让 PowerManager.FULL_WAKE_LOCK 将被释放。也许你也可以逃脱制作激活锁定静态

And you need to return START_STICKY from the method above if you want the service to keeps running after executing the code. If service is not kept alive the PowerManager.FULL_WAKE_LOCK will be released. Probably you can also get away making wakeLock static.

要启动服务使用:

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

- 编辑 -

--EDITED--

根据这里的主题:<一href=\"http://stackoverflow.com/questions/5018545/getapplication-vs-getapplicationcontext\">getApplication()与getApplicationContext()使用 getApplicationContext()获取上下文时,你可能会得到不同的上下文对象。尝试更改以下行:

As per the topic here: getApplication() vs. getApplicationContext() you may get different Context object when getting the context using getApplicationContext(). Try change the following line:

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

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

regrads。

regrads.

这篇关于服务正在被启动但OnCreate中或的OnStart不被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆