source

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

manysource 2022. 10. 14. 22:12

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

이 에러에 시달리고 있습니다.

08-08 11:42:53.179:E/AndroidRuntime(20288):원인:java.lang.인스턴스화예외: 클래스 com.example.local notification test를 인스턴스화할 수 없습니다.알림 서비스. 빈 생성자가 없습니다.

왜 이런 오류가 발생하는지 모르겠어요.

특정 시간에 알림을 표시하려고 합니다.시간을 검색한 결과 이 오래된 스택오버플로우 질문이 발견되었습니다.다 해봤는데 코드가 에러가 나요.

이 문제를 해결할 수 있도록 도와주세요.

Main Activity 코드는 다음과 같습니다.

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

}

리마인더 서비스 코드는 다음과 같습니다.

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>

어디가 잘못됐는지 모르겠어요.제가 코드를 놓쳤나요?

다음 인수를 사용하지 않는 빈 생성자를 클래스에 추가해야 합니다.

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

설명서에서 설명:

name는 워커 스레드의 이름을 붙이기 위해 사용됩니다.

메모: 이것은 인텐트 서비스에만 해당됩니다.

서비스가 내부 클래스/네스트 클래스로 선언된 경우 클래스를 정적으로 만들어야 합니다.

그렇지 않으면 컨스트럭터가 올바른 경우에도 오류가 발생합니다.

설명.

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

내부 클래스 static을 선언하면 외부 클래스로부터 독립됩니다.

IntentService 기본 인수 없음 생성자 선언

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

기본 인수 없음 생성자를 ReminderService 클래스에 추가해야 합니다.사용자가 직접 생성자를 작성하지 않은 경우에만 암시적으로 추가됩니다.여기를 참조해 주세요.http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

언급URL : https://stackoverflow.com/questions/11859403/no-empty-constructor-when-create-a-service