javaandroidnotificationsandroid-jobscheduler

Android app crashes when using Notification with JobScheduler


I have been recently trying to make the app display a notification every 5 seconds even when it is closed for testing purpose, so im using JobService to do it:


public class Job1 extends JobService {

    private boolean cancelled  = false;
    public static final String tag = "Job";
    private int id = 0;

    private void createChannel(String id, CharSequence name, int imp) {
           NotificationChannel channel = new NotificationChannel(id, name ,  imp );
           NotificationManager nm = getSystemService(NotificationManager.class);
           nm.createNotificationChannel(channel);      
    }

    private void display(int id , CharSequence channel_id, String content, String title , Context ctx){

        createChannel((String)channel_id , channel_id , NotificationManager.IMPORTANCE_HIGH);

        NotificationCompat.Builder nb = new NotificationCompat.Builder(ctx, (String) channel_id)
                .setSmallIcon(R.drawable.ic_work_black_24dp)
                .setContentText(content)
                .setContentTitle(title)
                .setPriority(NotificationCompat.PRIORITY_MAX);


        NotificationManagerCompat nmc = NotificationManagerCompat.from(ctx);
        nmc.notify(id , nb.build() );
      }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i(tag, "Job has been started");
        Job(params);

        return true;
    }

    private void Job(JobParameters params){


        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    Log.i(tag, "Job is Running");
                   ///////////////////////////////////////////////////
                    //the crash begin here.

                    display(id++ , "channel1" , "Description" , "title" , this);
                    ////////////////////////////////////////////////////////////////

                    try {

                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();

        //jobFinished(params , true);
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i(tag, "Job has been cancelled");
        cancelled = true;
        return true;
    }
}

Code to call the job:

ComponentName cname = new ComponentName(this, Job1.class);
            JobInfo jinfo = new JobInfo.Builder(1, cname)
                    .setRequiresCharging(false)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setPersisted(true)
                    .build();

            JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
            int result = scheduler.schedule(jinfo);
            if (result == JobScheduler.RESULT_SUCCESS) {
                Log.i("job", "scheduled");
            } else {
                Log.i("job", "failed");
            }

and of course i have also add the service name with the permissions in AndroidManifest.xml

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

 <service android:name=".Job1"
            android:permission="android.permission.BIND_JOB_SERVICE" />

When i try to use the notifications function alone, it works perfectly for example using it with just a button, and when i remove the line that call display function in Job the job work, but when i use the notification with it, it crash the whole app, so what could be the problem ?


Solution

  • After looking at logcat, and reading carefully, i finally got the solution

    The main problem was from the thread itself inside that JobService, when i try to make a new notification the app crashes with this info:

    java.lang.RuntimeException: Can't create handler inside thread Thread[Thread-2,5,main] that has not called Looper.prepare()
    

    The Solution is to make a new Thread Class and calling Looper.prepare()

    so the new Thread code will be this class:

    public class TestThread extends Thread{
    
        private int id = 0;
    
        private Context ctx;
    
        public TestThread(Context ctx){
            this.ctx = ctx;
        }
    
        public void run(){
    
            //this line has solved the issue
            Looper.prepare();
    
            while(true){
    
                Log.i("Thread" , "Thread is currently running in background :)");
    
                // my notifciation class
                (new Notifications()).displayNot(id++ , "channel6", "Content" , "title" , ctx);
    
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    

    and now we use this class from the job , in my case inside Job function:

    private void Job(JobParameters params){
    
            Thread thread = new TestThread(this);
            thread.start();
    
            if(!thread.isAlive()){
                jobFinished(params , true);
            }
    
        }