Java Android应用程序在与JobScheduler一起使用通知时崩溃

Java Android应用程序在与JobScheduler一起使用通知时崩溃,java,android,notifications,android-jobscheduler,Java,Android,Notifications,Android Jobscheduler,我最近一直在尝试让应用程序每5秒显示一次通知,即使它出于测试目的而关闭,所以我使用JobService来实现: public class Job1 extends JobService { private boolean cancelled = false; public static final String tag = "Job"; private int id = 0; private void createChannel(String id, Ch

我最近一直在尝试让应用程序每5秒显示一次通知,即使它出于测试目的而关闭,所以我使用JobService来实现:


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

调用作业的代码:

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");
            }
当然,我还添加了具有AndroidManifest.xml中权限的服务名称

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

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


当我尝试单独使用通知功能时,它工作得非常好,例如,只需一个按钮就可以使用它,当我在
Job
中删除调用
display
功能的行时,作业工作正常,但当我使用通知时,它会使整个应用程序崩溃,那么会出现什么问题呢?

查看logcat后,仔细阅读,我终于找到了答案

主要问题来自
JobService
中的线程本身,当我尝试发出新通知时,应用程序会因以下信息而崩溃:

java.lang.RuntimeException: Can't create handler inside thread Thread[Thread-2,5,main] that has not called Looper.prepare()
解决方案是创建一个新的线程类并调用
Looper.prepare()

因此,新的线程代码将是此类:

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

现在我们使用job中的这个类,在我的例子中,在
job
函数中:

private void Job(JobParameters params){

        Thread thread = new TestThread(this);
        thread.start();

        if(!thread.isAlive()){
            jobFinished(params , true);
        }

    }

使用Logcat检查与崩溃相关的堆栈跟踪:。仅当问题与android studio IDE本身相关时,请添加
android studio
标记。还请提供您需要的Logcat错误消息got@Zain谢谢,这个问题与IDE无关,在查看
logcat