很遗憾,应用已停止无法启动服务

时间:2017-11-03 14:00:01

标签: android android-studio-3.0

我尝试在Android studio 3.0中使用视频教程创建一个警报,我做了同样的事情,应用程序将运行,但是当我点击“警报”时它将被关闭。任何人都告诉我,在哪里问题是什么? 我曾使用Emulator API 22和23进行过尝试。

我当然不是,但我认为,问题应该在RingtonePlayingservice和getString中,因为它给出了一个错误“方法调用getString可能会产生java.lang.nullpointer” 但我,我不确定,如果问题是,我该如何解决?

我的主动:

package com.example.standard.alarm;

public class MainActivity extends AppCompatActivity {

//to make our Alarmmanager;
AlarmManager alarm_manager;
DatePicker alarm_datepicker;
TimePicker alarm_timepicker;
TextView update_text;
Context context;
PendingIntent pending_intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.context = this;
      //initialize our Alarmmanager
    alarm_manager = (AlarmManager) getSystemService(ALARM_SERVICE);

    //initialize our DatePicker
    alarm_datepicker = findViewById(R.id.datePicker);
    alarm_timepicker = findViewById(R.id.timePicker);

    //initialize our textupdate
    update_text = findViewById(R.id.update_text);

    //Create an instance of c Calender
    final Calendar calendar = Calendar.getInstance();

    final Intent my_intent = new Intent(this.context , Alarm_Receiver.class);



    Button alarm_on = findViewById(R.id.alarm_on);


    alarm_on.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (VERSION.SDK_INT >= 23 ) {
                calendar.set(Calendar.YEAR, alarm_datepicker.getYear());
                calendar.set(Calendar.MONTH, alarm_datepicker.getMonth());
                calendar.set(Calendar.DAY_OF_MONTH, alarm_datepicker.getDayOfMonth());
                calendar.set(Calendar.HOUR_OF_DAY, alarm_timepicker.getHour());
                calendar.set(Calendar.MINUTE, alarm_timepicker.getMinute());

                int year = alarm_datepicker.getYear();
                int month = alarm_datepicker.getMonth()+1;
                int day = alarm_datepicker.getDayOfMonth();
                int hour = alarm_timepicker.getHour();
                int minute = alarm_timepicker.getMinute();
                String yearst = String.valueOf(year);
                String monthst = String.valueOf(month);
                String dayst = String.valueOf(day);
                String hourst = String.valueOf(hour);
                String minutest = String.valueOf(minute);
                set_alarm_text("Alarm set on"+yearst+"/"+monthst+"/"+dayst+" - "+hourst+":"+minutest);
            }else{
                calendar.set(Calendar.YEAR , alarm_datepicker.getYear());
                calendar.set(Calendar.MONTH , alarm_datepicker.getMonth());
                calendar.set(Calendar.DAY_OF_MONTH , alarm_datepicker.getDayOfMonth());
                calendar.set(Calendar.HOUR_OF_DAY , alarm_timepicker.getCurrentHour());
                calendar.set(Calendar.MINUTE , alarm_timepicker.getCurrentMinute());


                int yearl = alarm_datepicker.getYear();
                int monthl = alarm_datepicker.getMonth()+1;
                int dayl = alarm_datepicker.getDayOfMonth();
                int hourl = alarm_timepicker.getCurrentHour();
                int minutel = alarm_timepicker.getCurrentMinute();
                String yearlst = String.valueOf(yearl);
                String monthlst = String.valueOf(monthl);
                String daylst = String.valueOf(dayl);
                String hourlst = String.valueOf(hourl);
                String minutelst = String.valueOf(minutel);
                set_alarm_text("Alarm set on"+yearlst+"/"+monthlst+"/"+daylst+" - "+hourlst+":"+minutelst);

            }

            my_intent.putExtra("extra","alarm on");
            pending_intent = PendingIntent.getBroadcast(MainActivity.this , 0 ,
                    my_intent, PendingIntent.FLAG_UPDATE_CURRENT);

            alarm_manager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    pending_intent);


        }
    });


    Button alarm_off = findViewById(R.id.alarm_off);
    alarm_off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            set_alarm_text("Alarm Off");

            alarm_manager.cancel(pending_intent);

            my_intent.putExtra("extra","alarm off");

            sendBroadcast(my_intent);

        }
    });

}

private void set_alarm_text(String output) {

    update_text.setText(output);

 }
}

我的服务类是:

public class RingtonePlayingService extends Service {

MediaPlayer media_song;
int startId;
Boolean isRunning;
@Nullable
@Override
public IBinder onBind(Intent intent){return null;}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);


    //fetch the extra string values
    String state = intent.getExtras().getString("extra");

    Log.e("Ringtone extra is",state);

    assert state != null;
    switch (state) {
        case "alarm on":
            startId = 1;
            break;
        case "alarm off":
            startId = 0;
            break;
        default:
            startId = 0;
            break;
    }



    if (!this.isRunning && startId == 1){


        media_song = MediaPlayer.create(this, R.raw.penii);
        media_song.start();

        this.isRunning = true;
        this.startId = 0;


    }else if (this.isRunning && startId == 0){

        media_song.stop();
        media_song.reset();

        this.isRunning = false;
        this.startId = 0;


    }else if (!this.isRunning && startId == 0){
        this.isRunning = false;
        this.startId = 0;

    }else if (this.isRunning && startId == 1){


        this.isRunning = true;
        this.startId = 1;


    }else {

    }



    return START_NOT_STICKY;

}

@Override
public void onDestroy() {
    super.onDestroy();
    this.isRunning = false;
 }


}

我的接收者是:

package com.example.standard.alarm;



public class Alarm_Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Log.e("Hi we are in receiver","Yay correct");

    String get_your_String = intent.getExtras().getString("extra");

    Log.e("what is the keay", get_your_String);

    Intent service_intent = new Intent(context, RingtonePlayingService.class);

    service_intent.putExtra("extra", get_your_String);

    context.startService(service_intent);
 }
}

和我的清单:

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

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

    <receiver android:name=".Alarm_Receiver" />

    <service android:name=".RingtonePlayingService"
        android:enabled="true">
    </service>

</application>

</manifest>

我的MainActivity XML是:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.standard.alarm.MainActivity">




    <DatePicker
    android:id="@+id/datePicker"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    <Button
    android:id="@+id/alarm_on"
    android:clickable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:text="alarm on"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/datePicker"
    android:layout_marginLeft="8dp" />

    <Button
    android:id="@+id/alarm_off"
    android:clickable="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:text="alarm off"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/datePicker"
    android:layout_marginRight="8dp" />

    <TextView
    android:id="@+id/update_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="45dp"
    android:text="@string/did_you_set_the_alarm"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/datePicker" />

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="match_parent"
        android:layout_height="310dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/update_text" />




</android.support.constraint.ConstraintLayout>

和Logcats中的错误:

FATAL EXCEPTION: main
                                                                      Process: com.example.standard.alarm, PID: 4001
                                                                      java.lang.RuntimeException: Unable to start service com.example.standard.alarm.RingtonePlayingService@e431d8d with Intent { cmp=com.example.standard.alarm/.RingtonePlayingService (has extras) }: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
                                                                          at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3027)
                                                                          at android.app.ActivityThread.-wrap17(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:148)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference
                                                                          at com.example.standard.alarm.RingtonePlayingService.onStartCommand(RingtonePlayingService.java:49)
                                                                          at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3010)
                                                                          at android.app.ActivityThread.-wrap17(ActivityThread.java) 
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1442) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                          at android.os.Looper.loop(Looper.java:148) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

1 个答案:

答案 0 :(得分:0)

您还将MainActivity代码放在服务代码的位置...... 除了你似乎想要在null对象上调用booleanValue()函数。在你的RingtonePlayingService的第49行