서비스를 만들 때 빈 생성자가 없습니다.


98

이 오류로 어려움을 겪고 있습니다.

08-08 11 : 42 : 53.179 : E / AndroidRuntime (20288) : 원인 : java.lang.InstantiationException : com.example.localnotificationtest.ReminderService 클래스를 인스턴스화 할 수 없습니다. 빈 생성자 없음

이 오류가 발생하는 이유를 이해할 수 없습니다.

특정 시간에 알림을 표시하려고하는데 시간을 검색 한 후이 오래된 stackoverflow 질문을 찾았습니다 . 나는 모든 것을 시도했지만 내 코드는 오류를 제공합니다.

이 문제를 해결하도록 도와주세요.

내 MainActivity 코드는 다음과 같습니다.

public class MainActivity extends Activity {
    int mHour, mMinute;
    ReminderService reminderService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        reminderService = new ReminderService("ReminderService");

        TimePickerDialog dialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);
        dialog.show();
    }

    TimePickerDialog.OnTimeSetListener mTimeSetListener =  new OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker v, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;

            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, Calendar.YEAR);
            c.set(Calendar.MONTH, Calendar.MONTH);
            c.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH);
            c.set(Calendar.HOUR_OF_DAY, mHour);
            c.set(Calendar.MINUTE, mMinute);
            c.set(Calendar.SECOND, 0);

            long timeInMills = c.getTimeInMillis();

            Intent intent = new Intent(MainActivity.this, ReminderService.class);
            PendingIntent pendingIntent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
            alarmManager.set(AlarmManager.RTC, timeInMills, pendingIntent);
        }
    };

}

내 ReminderService 코드는 다음과 같습니다.

public class ReminderService extends IntentService {

    public ReminderService(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification.Builder builder = new Notification.Builder(this);

        builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Local Notification Ticker")
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle("Local Notification")
            .setContentText("This is content text.");
         Notification n = builder.getNotification();

         nm.notify(1, n);
    }

}

그리고 여기에 내 manifest.xml이 있습니다.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.localnotificationtest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"  android:label="@string/app_name"  android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity"  android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="ReminderService"></service>
    </application>

</manifest>

나는 내가 어디로 잘못 가고 있는지 모른다. 코드가 누락 되었나요?

답변:


221

빈 생성자를 클래스에 추가해야합니다. 즉, 인수가없는 생성자를 추가해야합니다 .

public ReminderService() {
    super("ReminderService");
}

설명서설명 :

name작업자 스레드의 이름을 지정하는 데 사용됩니다.

참고 : 이는 의도 서비스에만 적용됩니다.


9
굵게 그 인수없이 생성자
Pratik Butani

44

서비스를 내부 클래스 / 중첩 클래스 로 선언 한 경우 클래스를 정적 으로 만들어야합니다.

그것 없이는 생성자가 정확하더라도 오류가 발생합니다.

설명

그 이유는 외부 클래스의 컨텍스트에서만 내부 클래스를 인스턴스화 할 수 있으므로 먼저 외부 클래스의 인스턴스를 만들어야하기 때문입니다.

내부 클래스를 정적으로 선언하면 외부 클래스와 독립적입니다.


이 문서는 어디에 있습니까?
Ciro Santilli 郝海东 冠状 病 六四 事件 法轮功

문서화되어 있는지는 모르겠지만 내부 비 정적 클래스를 인스턴스화하려면 먼저 외부 클래스를 인스턴스화해야합니다. 이제 서비스를 시작하면 인스턴스가 시스템에 의해 생성되므로 먼저 외부 클래스에서 인스턴스를 만들어야한다는 것을 알지 못하므로 충돌이 발생합니다. 그러나이 경우 오류는 실제로 오해의 소지가 있습니다. 한 번 봐 걸릴 stackoverflow.com/questions/70324/...을
마리아 Klühspies에게

32

IntentService에 대한 인수없는 기본 생성자 선언

public class ReminderService extends IntentService {
    public ReminderService() {
      super("ReminderService");
    }
}

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.