Search in sources :

Example 46 with NonNull

use of androidx.annotation.NonNull in project android-job by evernote.

the class Device method getNetworkType.

/**
 * Checks the network condition of the device and returns the best type. If the device
 * is connected to a WiFi and mobile network at the same time, then it would assume
 * that the connection is unmetered because of the WiFi connection.
 *
 * @param context Any context, e.g. the application context.
 * @return The current network type of the device.
 */
@NonNull
@SuppressWarnings("deprecation")
public static JobRequest.NetworkType getNetworkType(@NonNull Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo;
    try {
        networkInfo = connectivityManager.getActiveNetworkInfo();
    } catch (Throwable t) {
        return JobRequest.NetworkType.ANY;
    }
    if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
        return JobRequest.NetworkType.ANY;
    }
    boolean metered = ConnectivityManagerCompat.isActiveNetworkMetered(connectivityManager);
    if (!metered) {
        return JobRequest.NetworkType.UNMETERED;
    }
    if (isRoaming(connectivityManager, networkInfo)) {
        return JobRequest.NetworkType.CONNECTED;
    } else {
        return JobRequest.NetworkType.NOT_ROAMING;
    }
}
Also used : NetworkInfo(android.net.NetworkInfo) ConnectivityManager(android.net.ConnectivityManager) NonNull(androidx.annotation.NonNull)

Example 47 with NonNull

use of androidx.annotation.NonNull in project android-job by evernote.

the class JobCreatorHolderTest method createJobSucceedsWhenCreatorListIsModifiedConcurrently.

@Test
public void createJobSucceedsWhenCreatorListIsModifiedConcurrently() {
    // This test verifies that modifying the list of job-creators while
    // another thread is in the middle of JobCreatorHolder#createJob(String)
    // is safe, in that createJob will finish unexceptionally.
    // 
    // We'll test thread-safety by beginning iteration through the
    // job-creator list, then adding another creator while the iterator
    // is active.  If we are thread-safe, then iteration will complete
    // without an exception.
    // 
    // To coordinate this, we'll need a custom job creator that blocks
    // until it receives a signal to continue.  A "reader" thread will
    // invoke "createJob", iterating over the list, and blocking. While
    // the reader is blocked, a "mutator" thread will modify the creator
    // list, then signal the reader thread to resume.  Any
    // ConcurrentModificationException will be caught and stored.  When
    // both threads are finished, we can verify that no error was thrown.
    final Lock lock = new ReentrantLock();
    final Condition listModified = lock.newCondition();
    final Condition iterationStarted = lock.newCondition();
    final AtomicReference<Throwable> error = new AtomicReference<>();
    final AtomicBoolean isIteratorActive = new AtomicBoolean(false);
    class BlockingJobCreator implements JobCreator {

        @Override
        public Job create(@NonNull String tag) {
            lock.lock();
            try {
                isIteratorActive.set(true);
                iterationStarted.signal();
                listModified.awaitUninterruptibly();
            } finally {
                lock.unlock();
            }
            return null;
        }
    }
    class Mutator extends Thread {

        @Override
        public void run() {
            waitUntilIterationStarted();
            holder.addJobCreator(mockJobCreator);
            signalListModified();
        }

        private void waitUntilIterationStarted() {
            lock.lock();
            try {
                if (!isIteratorActive.get()) {
                    iterationStarted.awaitUninterruptibly();
                }
            } finally {
                lock.unlock();
            }
        }

        private void signalListModified() {
            lock.lock();
            try {
                listModified.signal();
            } finally {
                lock.unlock();
            }
        }
    }
    class Reader extends Thread {

        @Override
        public void run() {
            try {
                holder.createJob("SOME_JOB_TAG");
            } catch (Throwable t) {
                error.set(t);
            }
        }
    }
    holder.addJobCreator(new BlockingJobCreator());
    Mutator mutator = new Mutator();
    Reader reader = new Reader();
    reader.start();
    mutator.start();
    join(mutator);
    join(reader);
    assertThat(error.get()).isNull();
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Condition(java.util.concurrent.locks.Condition) AtomicReference(java.util.concurrent.atomic.AtomicReference) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NonNull(androidx.annotation.NonNull) Test(org.junit.Test)

Example 48 with NonNull

use of androidx.annotation.NonNull in project android-job by evernote.

the class JobExecutionTest method verifyCanceledJobNotRescheduled.

@Test
public void verifyCanceledJobNotRescheduled() {
    final AtomicBoolean onRescheduleCalled = new AtomicBoolean(false);
    final Job job = new Job() {

        @NonNull
        @Override
        protected Result onRunJob(@NonNull Params params) {
            manager().cancelAll();
            return Result.RESCHEDULE;
        }

        @Override
        protected void onReschedule(int newJobId) {
            onRescheduleCalled.set(true);
        }
    };
    JobCreator jobCreator = new JobCreator() {

        @Override
        public Job create(@NonNull String tag) {
            return job;
        }
    };
    manager().addJobCreator(jobCreator);
    final String tag = "something";
    final int jobId = new JobRequest.Builder(tag).setExecutionWindow(200_000L, 400_000L).build().schedule();
    executeJob(jobId, Job.Result.RESCHEDULE);
    assertThat(manager().getAllJobRequestsForTag(tag)).isEmpty();
    assertThat(manager().getJobRequest(jobId)).isNull();
    assertThat(manager().getJobRequest(jobId, true)).isNull();
    assertThat(onRescheduleCalled.get()).isFalse();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NonNull(androidx.annotation.NonNull) Test(org.junit.Test)

Example 49 with NonNull

use of androidx.annotation.NonNull in project android-job by evernote.

the class PlatformWorker method doWork.

@NonNull
@Override
public Result doWork() {
    final int jobId = getJobId();
    if (jobId < 0) {
        return Result.failure();
    }
    try {
        JobProxy.Common common = new JobProxy.Common(getApplicationContext(), CAT, jobId);
        JobRequest request = common.getPendingRequest(true, true);
        if (request == null) {
            return Result.failure();
        }
        Bundle transientBundle = null;
        if (request.isTransient()) {
            transientBundle = TransientBundleHolder.getBundle(jobId);
            if (transientBundle == null) {
                CAT.d("Transient bundle is gone for request %s", request);
                return Result.failure();
            }
        }
        Job.Result result = common.executeJobRequest(request, transientBundle);
        if (Job.Result.SUCCESS == result) {
            return Result.success();
        } else {
            return Result.failure();
        }
    } finally {
        TransientBundleHolder.cleanUpBundle(jobId);
    }
}
Also used : JobProxy(com.evernote.android.job.JobProxy) JobRequest(com.evernote.android.job.JobRequest) Bundle(android.os.Bundle) Job(com.evernote.android.job.Job) NonNull(androidx.annotation.NonNull)

Example 50 with NonNull

use of androidx.annotation.NonNull in project android-job by evernote.

the class DailyJobTest method verifyRequirementsEnforcedSkipsJob.

@Test
public void verifyRequirementsEnforcedSkipsJob() {
    long time = 1L;
    final AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    manager().addJobCreator(new JobCreator() {

        @Override
        public Job create(@NonNull String tag) {
            return new DailyJob() {

                @NonNull
                @Override
                protected DailyJobResult onRunDailyJob(@NonNull Params params) {
                    atomicBoolean.set(false);
                    return DailyJobResult.SUCCESS;
                }
            };
        }
    });
    int jobId = DailyJob.schedule(new JobRequest.Builder("any").setRequiresCharging(true).setRequirementsEnforced(true), time, time);
    assertThat(manager().getAllJobRequests()).hasSize(1);
    executeJob(jobId, Job.Result.SUCCESS);
    assertThat(manager().getAllJobRequests()).hasSize(1);
    assertThat(atomicBoolean.get()).isTrue();
    // now verify that the job is called without the requirement
    manager().cancelAll();
    jobId = DailyJob.schedule(new JobRequest.Builder("any").setRequiresCharging(false).setRequirementsEnforced(true), time, time);
    assertThat(manager().getAllJobRequests()).hasSize(1);
    executeJob(jobId, Job.Result.SUCCESS);
    assertThat(manager().getAllJobRequests()).hasSize(1);
    assertThat(atomicBoolean.get()).isFalse();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NonNull(androidx.annotation.NonNull) Test(org.junit.Test)

Aggregations

NonNull (androidx.annotation.NonNull)1197 View (android.view.View)191 ArrayList (java.util.ArrayList)154 Context (android.content.Context)128 Nullable (androidx.annotation.Nullable)128 TextView (android.widget.TextView)117 Intent (android.content.Intent)115 List (java.util.List)110 Recipient (org.thoughtcrime.securesms.recipients.Recipient)109 IOException (java.io.IOException)103 Bundle (android.os.Bundle)102 WorkerThread (androidx.annotation.WorkerThread)94 LayoutInflater (android.view.LayoutInflater)89 RecipientId (org.thoughtcrime.securesms.recipients.RecipientId)82 AlertDialog (androidx.appcompat.app.AlertDialog)76 Log (org.signal.core.util.logging.Log)76 Cursor (android.database.Cursor)68 ViewGroup (android.view.ViewGroup)65 LinkedList (java.util.LinkedList)64 Stream (com.annimon.stream.Stream)62