0

当我开始时JobIntentService,它工作正常,但进入手机睡眠后它会在一段时间后暂停。当我解锁手机时,它又开始工作了。

我想在后台有一个很长的任务,它不能暂停或停止。

这是我的JobInteneService

 public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, ExampleJob.class, 1, work);
    }

    @Override
    public void onCreate() {

        Log.d(TAG, "onCreate() called");
        super.onCreate();
    }


    @Override
    protected void onHandleWork(@NonNull Intent intent)
    {
        cancelRingtone = Uri.parse("android.resource://com.example.myapplication/" + R.raw.cancel);
        cancelAlarm = RingtoneManager.getRingtone(this, cancelRingtone);

        while(running)
        {
            cancelAlarm.play();
            try
            {
                Thread.sleep(60000);
            }
            catch (Exception e)
            {
                Log.i(TAG, "onHandleWork: "+e);
                running=false;
            }
        }
    }

    @Override
    public void onDestroy() {

        Log.d(TAG, "onDestroy() called");
        super.onDestroy();
    }

这是MainActivity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActivityCompat.requestPermissions(this,new String[]{
                Manifest.permission.WAKE_LOCK
        }, 1);
    }

    public void click(View view)
    {
        Intent mIntent = new Intent(this, ExampleJob.class);
        ExampleJob.enqueueWork(this, mIntent);

    }

这是AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ExampleJob"
            android:permission="android.permission.BIND_JOB_SERVICE"/>

    </application>

使用此代码,我的手机将每分钟播放一次哔声。在手机睡眠模式下,我在半小时内数到最多 6 次哔声。我是否JobIntentService正确实施?如果JobIntentService不是为这项工作而设计的,我还应该使用什么?

4

0 回答 0