从广播接收器访问对象?

时间:2015-05-21 11:34:20

标签: android

这是我用来启动闹钟的广播接收器的源代码:

public class AlarmReceiver extends WakefulBroadcastReceiver {

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

    PendingIntent sender = PendingIntent.getBroadcast(context, 0, 
intent, 0);


    Uri alarmUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    if (alarmUri == null)
    {
        alarmUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    }
    Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
    ringtone.play();


    //intent to call the activity which shows on ringing
    Intent myIntent = new Intent(context, Time_Date.class);
    myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(myIntent);

    //display that alarm is ringing
    Toast.makeText(context, "Alarm Ringing...!!!", 
Toast.LENGTH_LONG).show();

    ComponentName comp = new ComponentName(context.getPackageName(),
            AlarmService.class.getName());
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);

}


}

从另一个班级,我试着打电话:

public void end(View view)
{
    ringtone.stop();


}

但是,这肯定是错误的方式,我只需要知道,调用它的最佳和最正确的方法是什么?

1 个答案:

答案 0 :(得分:0)

我建议使用两个public static函数访问一个private static Ringtone ringABC。 这两个函数你可以调用playRingtone和stopRingtone,如果有ringABC(播放),让他们先检查。 ( - >避免NullPointerExceptions或两个铃声播放)

编辑:

public class MyRingtone {
    private static Ringtone ringtone = null;

    public static boolean startRingtone(Context context) {
        if(ringtone == null) {
            Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            if (alarmUri == null) {
                alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
            ringtone = RingtoneManager.getRingtone(context, alarmUri);
            ringtone.play();

            return true;
        }
        else
            return false;
    }

    public static boolean stopRingtone() {
        if(ringtone != null) {
            ringtone.stop();
            ringtone = null;
            return true;
        }
        else
            return false;
    }
}