每日播放声音的Android App

时间:2015-04-20 02:23:53

标签: java android audio playback alarm

我怎样才能拥有一个每天在特定时间播放某种噪音或声音的Android应用程序?
到目前为止,我的代码包含一个按钮,可以在点击时播放噪音。

3 个答案:

答案 0 :(得分:1)

你必须创建服务 并且在服务中,您每隔10:00 AM从资产文件夹播放一首歌曲。 该服务将如下所示: MyService.java

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.Time;
import android.widget.Switch;
import android.widget.Toast;

import java.io.IOException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MyService extends Service {

    private int Annee;
    private int Mois;
    private int Jour;
    private int Heure;
    private  int Minute;
    boolean afficher=true;
    private Handler customHandler = new Handler();

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Non implementé");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) { 
        Toast.makeText(this,"Service demarré",Toast.LENGTH_LONG).show();
        customHandler.postDelayed(updateTimerThread, 3000 );
        super.onStart(intent, startId);
    }


    @Override
    public void onDestroy() {
        onStop();
        Toast.makeText(this,"Service arrété",Toast.LENGTH_LONG).show();
        customHandler.removeCallbacks(updateTimerThread);
        super.onDestroy();
    }

    public void onStop(){
    }
    private Runnable updateTimerThread = new Runnable() {
        public void run() {


            final Calendar cal = Calendar.getInstance();
                Annee = cal.get(Calendar.YEAR);
                Mois = cal.get(Calendar.MONTH)%12+1;
                Jour = cal.get(Calendar.DAY_OF_MONTH);
                Heure=cal.get(Calendar.HOUR_OF_DAY)%24+1;
                if(Heure==24)Heure=0;
                Minute=cal.get(Calendar.MINUTE);
                String min=Integer.toString(Minute);
                String heure=Integer.toString(Heure);
                String h=heure+":"+min;
                java.text.SimpleDateFormat simpleTimeFormat = new java.text.SimpleDateFormat("HH:mm");
                String h2 = null;
                try {
                    h2 = simpleTimeFormat.format(simpleTimeFormat.parse(h));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            String a, m, j;
            j = Integer.toString(Jour);
            m = Integer.toString(Mois);
            a = Integer.toString(Annee);
            String d = j + "/" + m + "/" + a;
            java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("dd/MM/yyyy");
            String d2 = null;
            try {
                d2 = simpleDateFormat.format(simpleDateFormat.parse(d));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            if (h2.equals("10:00")) {
                 if (afficher){
                    Intent intent =new Intent(getBaseContext(),AlertD.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra("Cle",cur.getString(0));
                    getApplication().startActivity(intent);
                afficher=false;}

          }}

            customHandler.postDelayed(this , 3000 );
        };

}

bootCompleted.java

 import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
 * Created by Mechalikh on 21/12/2014.
 */
public class BootCompleted extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)){
    Intent serviceIntent= new Intent(context,MyService.class);
    context.startService(serviceIntent);
}
    }

}

alertD.java(警报对话框)

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class AlertD extends Activity {
    MediaPlayer m;
    public static String cle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        m=new MediaPlayer();
        cle =getIntent().getStringExtra("Cle");
        final AlertDialog alertDialog =new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Votre rendez-vous");
        alertDialog.setMessage("Vous avez un rendez-vous dans UNE HEURE !");
        alertDialog.setButton("Arréter", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                m.stop();
                AlertD.super.onBackPressed();
            }
        });


        alertDialog.show();
        Alarme();
    }

    private void Alarme()  {

        try {
            if (m.isPlaying()) {
                m.stop();
                m.release();
                m = new MediaPlayer();
            }
            AssetFileDescriptor descriptor = getAssets().openFd("Alarm.mp3");
            m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();
            m.prepare();
            m.setVolume(1f, 1f);
            m.setLooping(true);
            m.start();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}

了解更多信息,请参阅本教程 http://blog.vogella.com/2011/12/11/automatically-starting-services-in-android-after-booting/

答案 1 :(得分:1)

使用闹钟管理器并安排重复闹钟。

重复警报计划检查此演示:

https://developer.android.com/training/scheduling/alarms.html

答案 2 :(得分:0)

使用Alarm Manager并在您选择时设置不准确的重复闹铃。