6

我目前正在开发一个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 如下要求是启动服务并执行唤醒锁的所有代码。

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

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>

希望这可以帮助。

4

3 回答 3

9

您正在不同的过程中开始服务。

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

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

至于调试onCreate(),您必须在进程启动之后附加调试器,但在onCreate()调用之前。例如,您可以Thread.sleep()在开头onCreate()放置几秒钟,以便您可以附加调试器。

于 2013-05-21T12:58:52.850 回答
3

Which class are you extending? Service?

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)

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.

To start service use:

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

--EDITED--

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

by:

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

regrads.

于 2012-10-26T22:33:34.777 回答
0

只是一个说明:

onStart()方法已弃用,您应该onStartCommand()改用(仅当您使用Context.startService().

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

于 2012-10-26T22:37:33.513 回答