How to pass an audio file to a broadcast receiver and play it as an alarm

android android-layout

735 просмотра

2 ответа

I have an alarm app and I have a text view and when i press it, it will redirect me to the audio folder then i can choose a song and play it as an alarm. After i choose it, then click my set alarm button, it would crash after how many seconds. The error is pointing out to the broadcast receiver.

This is my Set Alarm Activity:

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

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
                + "/Audio/");
        intent.setDataAndType(uri, "audio/*");
        startActivityForResult(intent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data){

        if(requestCode == 1){

            if(resultCode == RESULT_OK){

                //the selected audio.
                Uri uri = data.getData();
                Intent n = new Intent(this, AlarmReceiver.class);
                n.putExtra("song", uri.toString());

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

Code for Broadcast Receiver:

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

    Intent in = new Intent();

    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), notification);
    r.play();
    Uri ir = in.getParcelableExtra("song");
    mp = MediaPlayer.create(context, ir);
    mp.start();
}

Logcat

08-21 04:05:35.011 1553-1571/system_process E/BluetoothAdapter: Bluetooth binder is null
08-21 04:05:35.012 1553-1571/system_process E/KernelCpuSpeedReader: Failed to read cpu-freq
java.io.FileNotFoundException: /sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state: open failed: ENOENT (No such file or directory)
    at libcore.io.IoBridge.open(IoBridge.java:452)
    at java.io.FileInputStream.<init>(FileInputStream.java:76)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
    at java.io.FileReader.<init>(FileReader.java:66)
    at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49)
    at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002)
    at com.android.server.am.BatteryStatsService.updateExternalStats(BatteryStatsService.java:1366)
    at com.android.server.am.BatteryStatsService$BatteryStatsHandler.handleMessage(BatteryStatsService.java:125)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.os.HandlerThread.run(HandlerThread.java:61)
    at com.android.server.ServiceThread.run(ServiceThread.java:46)
 Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
    at libcore.io.Posix.open(Native Method)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
    at libcore.io.IoBridge.open(IoBridge.java:438)
    at java.io.FileInputStream.<init>(FileInputStream.java:76) 
    at java.io.FileInputStream.<init>(FileInputStream.java:103) 
    at java.io.FileReader.<init>(FileReader.java:66) 
    at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49) 
    at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002) 
    at com.android.server.am.BatteryStatsService.updateExternalStats(BatteryStatsService.java:1366) 
    at com.android.server.am.BatteryStatsService$BatteryStatsHandler.handleMessage(BatteryStatsService.java:125) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.os.HandlerThread.run(HandlerThread.java:61) 
    at com.android.server.ServiceThread.run(ServiceThread.java:46) 
08-21 04:05:35.012 1553-1571/system_process E/KernelUidCpuTimeReader: Failed to read uid_cputime
  java.io.FileNotFoundException: /proc/uid_cputime/show_uid_stat: open failed: ENOENT (No such file or directory)
      at libcore.io.IoBridge.open(IoBridge.java:452)
      at java.io.FileInputStream.<init>(FileInputStream.java:76)
      at java.io.FileInputStream.<init>(FileInputStream.java:103)
      at java.io.FileReader.<init>(FileReader.java:66)
      at com.android.internal.os.KernelUidCpuTimeReader.readDelta(KernelUidCpuTimeReader.java:71)
      at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8031)
      at com.android.server.am.BatteryStatsService.updateExternalStats(BatteryStatsService.java:1366)
      at com.android.server.am.BatteryStatsService$BatteryStatsHandler.handleMessage(BatteryStatsService.java:125)
      at android.os.Handler.dispatchMessage(Handler.java:102)
      at android.os.Looper.loop(Looper.java:148)
      at android.os.HandlerThread.run(HandlerThread.java:61)
      at com.android.server.ServiceThread.run(ServiceThread.java:46)
   Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
      at libcore.io.Posix.open(Native Method)
      at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
      at libcore.io.IoBridge.open(IoBridge.java:438)
      at java.io.FileInputStream.<init>(FileInputStream.java:76) 
      at java.io.FileInputStream.<init>(FileInputStream.java:103) 
      at java.io.FileReader.<init>(FileReader.java:66) 
      at com.android.internal.os.KernelUidCpuTimeReader.readDelta(KernelUidCpuTimeReader.java:71) 
      at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8031) 
      at com.android.server.am.BatteryStatsService.updateExternalStats(BatteryStatsService.java:1366) 
      at com.android.server.am.BatteryStatsService$BatteryStatsHandler.handleMessage(BatteryStatsService.java:125) 
      at android.os.Handler.dispatchMessage(Handler.java:102) 
      at android.os.Looper.loop(Looper.java:148) 
      at android.os.HandlerThread.run(HandlerThread.java:61) 
      at com.android.server.ServiceThread.run(ServiceThread.java:46) 
08-21 04:05:35.012 1553-1571/system_process E/KernelWakelockReader: neither /proc/wakelocks nor /d/wakeup_sources exists
08-21 04:05:35.017 1553-1571/system_process W/BatteryStatsImpl: Couldn't get kernel wake lock stats
08-21 04:05:35.086 2268-10915/com.google.android.gms D/DropBoxEntryAddedChimeraService: User is not opted-in to Usage & Diagnostics.
08-21 04:05:54.610 1553-1575/system_process W/ProcessCpuTracker: Skipping unknown process pid 11191
08-21 04:05:54.610 1553-1575/system_process W/ProcessCpuTracker: Skipping unknown process pid 11196
08-21 04:06:00.026 1553-1567/system_process I/ProcessStatsService: Prepared write state in 1ms
08-21 04:06:00.052 1553-1565/system_process W/BroadcastQueue: Skipping deliver [foreground] BroadcastRecord{2cfd4a7 u-1 android.intent.action.TIME_TICK} to ReceiverList{53b0aef 10154 myapps.wycoco.com.alarmapp/10064/u0 remote:8835bce}: process crashing
08-21 04:06:47.744 2268-11950/com.google.android.gms I/EventLogChimeraService: Aggregate from 1471750607524 (log), 1471750607524 (data)
08-21 04:06:47.857 2268-11954/com.google.android.gms D/DropBoxEntryAddedChimeraService: User is not opted-in to Usage & Diagnostics.
08-21 04:07:00.053 1553-1712/system_process W/BroadcastQueue: Skipping deliver [foreg
Автор: Anton Wycoco Источник Размещён: 08.11.2019 11:09

Ответы (2)


0 плюса

Create a global variable for song uri on your Set Alarm class.

Uri songUri;

On your onItemClick method change setDataAndType(uri, "*/*"); to setDataAndType(uri, "audio/*"); so the chooser may only display audio files for the user.

You will also have to change startActivity(Intent.createChooser(intent, "Open"); to startActivityForResult(Intent.createChooser(intent, "Open"), 1); this will allow you to get what ever was chosen from the chooser.

Override onActivityResult on the same class. Then set the songUri global variable.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (data != null) {
        songUri = data.getData();
    }
}

finally, put extra on the Intent that is pointing to the AlarmReceiver.class

intent.putExtra("song",songUri);

on your Broadcast Receiver class change mp = MediaPlayer.create(context, R.raw.closer); to this

try{
    mp = MediaPlayer.create(context, (Uri)intent.getParcelableExtra("song"));
}catch(NullPointerException e) {
    mp = MediaPlayer.create(context, R.raw.closer);
}

A NullPointerException will be triggered if no song is chosen that's because intent.getParcelableExtra("song") will be null. If a song is chosen place it on the try block and get the extra.

Автор: paperflyy Размещён: 21.08.2016 06:37

-1 плюса

Try this one.

 @Override
    public void onReceive(Context context, Intent intent)
    {
     AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            MediaPlayer player = MediaPlayer.create(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            try {
                player.setVolume((float) (audio.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0),
                        (float) (audio.getStreamVolume(AudioManager.STREAM_NOTIFICATION) / 7.0));
            } catch (Exception e) {
                e.printStackTrace();
            }

            player.start();
    }
Автор: Sabish.M Размещён: 20.08.2016 10:07
Вопросы из категории :
32x32