警报应用程序无法正常工作

时间:2016-08-04 20:39:17

标签: android alarmmanager

我创建了一个闹钟应用程序,当你设置它时,它会播放你选择的声音并给你一条消息,说明闹钟的设置时间。

问题是,我从来没有发出声音。 我在这里缺少什么?

编辑:对不起,这就是我的

这是MainActivity:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
AlarmManager alarmManager;
private PendingIntent pending_intent;

private TimePicker alarmTimePicker;
private static MainActivity inst;
private TextView alarmTextView;

private AlarmReceiver alarm;
private Context context;
Spinner spinner;
int richard_quote = 0;


@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  //  alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
  //  alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    this.context = this;

    //alarm = new AlarmReceiver();
    alarmTextView = (TextView) findViewById(R.id.alarmText);

    final Intent myIntent = new Intent(this.context, AlarmReceiver.class);

    // Get the alarm manager service
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    // set the alarm to the time that you picked
    final Calendar calendar = Calendar.getInstance();
    //calendar.add(Calendar.SECOND, 3);
    alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);

    //spinner creation
    Spinner spinner = (Spinner) findViewById(R.id.richard_spinner);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.dawkins_sounds, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    // Spinner click listener
    spinner.setOnItemSelectedListener(this);

    myIntent.putExtra("extra", "yes");
    myIntent.putExtra("quote id", String.valueOf(richard_quote));
    pending_intent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);






    Button start_alarm= (Button) findViewById(R.id.start_alarm);
    start_alarm.setOnClickListener(new View.OnClickListener() {
        @TargetApi(Build.VERSION_CODES.M)

        @Override
        public void onClick(View v) {

            calendar.set(Calendar.HOUR, alarmTimePicker.getHour());
            calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());
            calendar.set(Calendar.SECOND, 0);
         //   calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getHour());
         //   calendar.set(Calendar.MINUTE, alarmTimePicker.getMinute());

            final int hour = alarmTimePicker.getHour();
            final int minute = alarmTimePicker.getMinute();;

            String minute_string = String.valueOf(minute);
            String hour_string = String.valueOf(hour);

            if (minute < 10) {
                minute_string = "0" + String.valueOf(minute);
            }

            if (hour > 12) {
                hour_string = String.valueOf(hour - 12) ;
            }


          //  myIntent.putExtra("extra", "yes");
          //  myIntent.putExtra("quote id", String.valueOf(richard_quote));
         //   pending_intent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);


          //  alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pending_intent);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pending_intent);

         //   setAlarmText("Alarm ON ");

           setAlarmText("Alarm set to " + hour_string + ":" + minute_string);
        }

    });

    Button stop_alarm= (Button) findViewById(R.id.stop_alarm);
    stop_alarm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            myIntent.putExtra("extra", "no");
            myIntent.putExtra("quote id", String.valueOf(richard_quote));
            sendBroadcast(myIntent);

            alarmManager.cancel(pending_intent);
            setAlarmText("Alarm canceled");

            //setAlarmText("ID is " + richard_quote);
        }
    });

}

public void setAlarmText(String alarmText) {
    alarmTextView.setText(alarmText);
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


@Override
public void onStart() {
    super.onStart();
    inst = this;
}


@Override
public void onDestroy() {
    super.onDestroy();

    Log.e("MyActivity", "on Destroy");
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    //Toast.makeText(parent.getContext(), "Spinner item 3!" + id, Toast.LENGTH_SHORT).show();
    richard_quote = (int) id;
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback

}

}

这是AlarmReceiver

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    String state = intent.getExtras().getString("extra");
    Log.e("MyActivity", "In the receiver with " + state);

    String richard_id = intent.getExtras().getString("quote id");
    Log.e("Goat quote is" , richard_id);

    Intent serviceIntent = new Intent(context,RingtonePlayingService.class);
    serviceIntent.putExtra("extra", state);
    serviceIntent.putExtra("quote id", richard_id);

    context.startService(serviceIntent);
}

}

这是RingtonrPlayingService

public class RingtonePlayingService extends Service {

private boolean isRunning;
private Context context;
MediaPlayer mMediaPlayer;
private int startId;

@Override
public IBinder onBind(Intent intent)
{
    Log.e("MyActivity", "In the alarm service");
    return null;
}


@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{


    final NotificationManager mNM = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);

    Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification mNotify  = new Notification.Builder(this)
            .setContentTitle("alarm is talking" + "!")
            .setContentText("Click me!")
            .setSmallIcon(R.drawable.ic_action_call)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

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

    Log.e("what is going on here  ", state);

    assert state != null;
    switch (state) {
        case "no":
            startId = 0;
            break;
        case "yes":
            startId = 1;
            break;
        default:
            startId = 0;
            break;
    }

    // get richard's thing
    String richard_id = intent.getExtras().getString("quote id");
    Log.e("Service: goatid is " , richard_id);

    if(!this.isRunning && startId == 1) {
        Log.e("if there was not sound ", " and you want start");

        assert richard_id != null;
        if (richard_id.equals("0")) {

            int min = 1;
            int max = 2;

            Random r = new Random();
            int random_number = r.nextInt(max - min + 1) + min;
            Log.e("random number is ", String.valueOf(random_number));

            if (random_number == 1) {
               mMediaPlayer = MediaPlayer.create(this, R.raw.alarm2);
            }
            else if (random_number == 2) {
               mMediaPlayer = MediaPlayer.create(this, R.raw.alarm1);
            }

            else {
               mMediaPlayer = MediaPlayer.create(this, R.raw.alarm2);
            }
        }
        else if (richard_id.equals("1")) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.alarm2);
        }
        else if (richard_id.equals("2")) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.alarm1);
        }

        else {
            mMediaPlayer = MediaPlayer.create(this, R.raw.alarm2;
        }


        mMediaPlayer.start();

        mNM.notify(0, mNotify);

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

    }
    else if (!this.isRunning && startId == 0){
        Log.e("if there was not sound ", " and you want end");

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

    }

    else if (this.isRunning && startId == 1){
        Log.e("if there is sound ", " and you want start");

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

    }
    else {
        Log.e("if there is sound ", " and you want end");

        mMediaPlayer.stop();
        mMediaPlayer.reset();

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


    Log.e("MyActivity", "In the service");

    return START_NOT_STICKY;
}



@Override
public void onDestroy() {
    Log.e("JSLog", "on destroy called");
    super.onDestroy();

    this.isRunning = false;
}

}

1 个答案:

答案 0 :(得分:0)

您没有正确启动MediaPlayer。

通读本文,特别是关于将MediaPlayer与服务一起使用的部分:

https://developer.android.com/guide/topics/media/mediaplayer.html

基本上,步骤是

  1. 制作播放器
  2. 准备球员
  3. 开始播放
  4. 您跳过了步骤2,步骤2需要一些工作才能在从服务进行播放时正常运行。您也没有正确管理MediaPlayer资源。

    此处有更多详情:

    https://developer.android.com/reference/android/media/MediaPlayer.html

    具体说明(在页面顶部,刚好超过状态图)

      

    MediaPlayer对象必须先进入Prepared状态   可以开始播放。