【问题标题】:Service is being started but OnCreate or OnStart are not being called服务正在启动,但未调用 OnCreate 或 OnStart
【发布时间】:2012-10-17 04:56:10
【问题描述】:

我目前正在开发一个 android 项目,我正在尝试启动一项服务,并且该服务已经开始运行一些代码来初始化一些东西。

以下是我用于服务的代码。

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

唤醒锁始终为空,因为那段代码永远不会在 oncreate 或 onstart 中执行。我试过把它放在绑定函数中,但仍然没有乐趣。

当我进入 android 设置时,我可以看到我的应用程序正在运行服务,但我需要先初始化该代码,然后才能正常工作。

感谢您提供的任何帮助。

更新 由于前面的评论,我发现正在调用这些函数。由于某种原因,调试器没有被触发。

下面是显示如何根据请求创建服务器的代码。

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 如下要求是启动服务并执行唤醒锁的所有代码。

下面是启动服务的主要activity

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文件。

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

希望这会有所帮助。

【问题讨论】:

  • 你确定你的方法 onCreate() 和 onStart 没有被调用吗?由于其他原因,您的唤醒锁定可能为空。
  • 我在他们俩上都设置了断点,他们永远不会被解雇。但是我确实只是将 Log.d 放入代码中以确保它们被打印出来。那为什么会是空的
  • 你能告诉我们你是如何启动服务的吗?
  • 我已按要求添加了代码

标签: android service


【解决方案1】:

您正在不同的进程中启动服务。

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

调试器已附加到您的主进程。当新的启动时,它没有附加调试器,所以它会忽略你的断点。如果你想调试远程进程,你可以在 DDMS 透视图中通过 Eclipse 来完成。在设备下,您可以看到其进程。然后您可以选择一个并按调试选定的进程(绿色错误图标)。当您只想在某个时候开始调试应用时,这也很有用。

至于调试onCreate(),您必须在进程启动后,但在调用onCreate() 之前附加调试器。例如,您可以将一些 Thread.sleep() 放在 onCreate() 的开头几秒钟,这样您就可以附加调试器了。

【讨论】:

    【解决方案2】:

    你在扩展哪个类?服务?

    onStart() 方法仅用于旧的 Android 版本 (onStartCommand(),如下所示:

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

    如果您希望服务在执行代码后继续运行,则需要从上述方法中返回START_STICKY。如果服务没有保持活动状态,PowerManager.FULL_WAKE_LOCK 将被释放。也许你也可以将wakeLock设为静态。

    开始使用服务:

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

    --已编辑--

    根据此处的主题:getApplication() vs. getApplicationContext() 在使用getApplicationContext() 获取上下文时,您可能会得到不同的Context 对象。尝试更改以下行:

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

    作者:

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

    毕业了。

    【讨论】:

    • 谢谢尝试了这个,但这并没有被执行,我放了一个 Log.d 但没有任何输出,只有 onCreate 被调用。
    • 你在扩展哪个类?
    • 我正在使用extends Service
    • 如何启动服务?
    • 我已经在我的答案中添加了如何启动服务。
    【解决方案3】:

    请注意:

    onStart() 方法已弃用,您应该改用onStartCommand()(仅当您使用Context.startService() 启动服务时才会调用它。

    但是,如果您的服务确实运行(但只运行一次),则应该调用 onCreate()

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 2012-12-20
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多