Класс JobService не имеет конструктора с нулевым аргументом - PullRequest
0 голосов
/ 14 апреля 2020

У меня есть внутренний класс с именем DownloadJobNotification, который расширяет JobService, который должен выполнять уведомление, отображаемое один раз в день или при нажатии кнопки загрузки. я добавил службу в манифест и все же по какой-то причине я получаю эту ошибку

java.lang.RuntimeException: Unable to instantiate service com.example.jobcodlabhomework.MainActivity$DownloadJobNotification: java.lang.InstantiationException: java.lang.Class<com.example.jobcodlabhomework.MainActivity$DownloadJobNotification> has no zero argument constructor

вот мой код:


private const val CHANNEL_ID = "JOB_CHANNEL_ID"
private const val NOTIFICATION_CHANNEL_ID = "DOWNLOAD_NOTIFICATION"
private lateinit var mNotifyManager: NotificationManager
private lateinit var mScheduler: JobScheduler
private const val JOB_ID = 0
private lateinit var jobNotification: MainActivity.DownloadJobNotification
private const val NOTIFICATION_ID = 12
private lateinit var jobInfo: JobInfo.Builder


class MainActivity : AppCompatActivity() {
    inner class DownloadJobNotification : JobService() {

        fun createNotificationChannel() {
            mNotifyManager =
                this@MainActivity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationChannel = NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "Download Job Notification0",
                    NotificationManager.IMPORTANCE_HIGH
                )
                notificationChannel.enableVibration(true)
                notificationChannel.enableLights(true)
                notificationChannel.description = "Download Job Notification"


                mNotifyManager.createNotificationChannel(notificationChannel)
            }
        }

        override fun onStopJob(params: JobParameters?): Boolean {
            return true
        }

        @RequiresApi(Build.VERSION_CODES.O)
        override fun onStartJob(params: JobParameters?): Boolean {
            Log.d("MainActivity", "Job Started")
            val notification = Notification.Builder(this, CHANNEL_ID)
                .setAutoCancel(true)
                .setContentText("Download in progress")
                .setContentTitle("Performing Work")
                .setSmallIcon(R.drawable.ic_launcher_background)

            mNotifyManager.notify(NOTIFICATION_ID, notification.build())
            return false
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        jobNotification = DownloadJobNotification()
        //Log.d("MainActivity", "$mNotifyManager")
        jobNotification.createNotificationChannel()
        jobInfo = JobInfo.Builder(
            JOB_ID,
            ComponentName(packageName, DownloadJobNotification::class.java.name)
        )
            //.setRequiresDeviceIdle(true)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
            .setPeriodic(86400000)
        button1.setOnClickListener {
            performDownload()
        }

    }

    private fun performDownload() {
        mScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
        mScheduler.schedule(jobInfo.build())
    }
}

вот мой манифест:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jobcodlabhomework">

    <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=".MainActivity$DownloadJobNotification"
            android:permission="android.permission.BIND_JOB_SERVICE" />

    </application>

</manifest>

вот логкат:

2020-04-14 13:16:07.102 11817-11817/com.example.jobcodlabhomework E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.jobcodlabhomework, PID: 11817
    java.lang.RuntimeException: Unable to instantiate service com.example.jobcodlabhomework.MainActivity$DownloadJobNotification: java.lang.InstantiationException: java.lang.Class<com.example.jobcodlabhomework.MainActivity$DownloadJobNotification> has no zero argument constructor
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3176)
        at android.app.ActivityThread.-wrap5(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: java.lang.InstantiationException: java.lang.Class<com.example.jobcodlabhomework.MainActivity$DownloadJobNotification> has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at android.app.ActivityThread.handleCreateService(ActivityThread.java:3173)
        at android.app.ActivityThread.-wrap5(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1567) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6119) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

1 Ответ

1 голос
/ 14 апреля 2020

Вы не можете сделать работу классом inner. Это также означает, что у вас нет доступа к внешней деятельности. Но поскольку JobService является службой, вы можете просто использовать this для действий, связанных с контекстом (например, для получения системных служб).

Таким образом, вместо

mNotifyManager =
                this@MainActivity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

вы можете просто использовать:

mNotifyManager =
                this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

Не имеет особого смысла помещать его как вложенный класс. Вы можете просто отделить его от действия.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...