android 弹出进度条对话框的方法

实际代码是做和做FM闹钟相关功能,收藏防止以后查阅

new AlertDialog.Builder(this)
    .setTitle(getString(R.string.info))
    .setMessage(getString(R.string.auto_search_confirm))
    .setPositiveButton(android.R.string.ok,
      new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int w) {
        dialog.dismiss();
        searchProcess();
       }

       private void searchProcess() {
        LinearLayout myLayout;
        LayoutInflater layoutInflater;
        AlertDialog.Builder dialogBuilder;

        myLayout = new LinearLayout(SetAlarm.this);
        layoutInflater=(LayoutInflater) getSystemService(SetAlarm.this.LAYOUT_INFLATER_SERVICE);
        myLayout=(LinearLayout) layoutInflater.inflate(R.layout.progress_dialog, null);

        progressBar=(ProgressBar)myLayout.findViewById(R.id.progressBar);
        progressBar.setMax(205);

        dialogBuilder = new AlertDialog.Builder(SetAlarm.this);
        dialogBuilder.setView(myLayout);
        dialogBuilder.setMessage(SetAlarm.this.getString(R.string.channel_searching));
        dialog = dialogBuilder.show();
        dialog.setCancelable(false);
        if (localAudioManager != null && localAudioManager.isWiredHeadsetOn()) {
         registerReceiver(searchBroadcast, new IntentFilter(SEARCH_DONE));
         registerReceiver(searchBroadcast, new IntentFilter(SET_PROGRESS));
         mFMAlarmPref.searchChannel();
        } else {
         if(dialog != null && dialog.isShowing())
         {
          dialog.dismiss();
         }
         Toast toast = Toast.makeText(SetAlarm.this, SetAlarm.this.getString(R.string.plug_in_headset), Toast.LENGTH_LONG);
         ToastMaster.setToast(toast);
         toast.show();
        }
       }
      })
    .setNegativeButton(android.R.string.cancel,
      new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialog,
         int which) {
        mFMRingState.setChecked(false);
        mAlarmPref.setEnabled(true);
        dialog.dismiss();
       }

      }).show();


 

static String SEARCH_DONE = "com.android.deskclock.search_done";
	static String SET_PROGRESS = "com.android.deskclock.set_progress";
	static String FMSERVICE = "net.kindroid.aidl.service.IFMService";
	static String PROGRESS = "progress";
	private AlertDialog dialog;
	private ProgressBar progressBar;
	final BroadcastReceiver searchBroadcast = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(SEARCH_DONE)) {
				progressBar.setProgress(205);
				mFMAlarmPref.updateEntres();
				if(mFMAlarmPref.mEntries != null && mFMAlarmPref.mEntries.length > 0)
				{
					mFMAlarmPref.setEnabled(true);
				} else
				{
					mFMAlarmPref.setEnabled(false);
				}
				if(dialog != null && dialog.isShowing())
				{
					dialog.dismiss();
				}
			} else if (action.equals(SET_PROGRESS)) {
				int progress = intent.getIntExtra(PROGRESS, 205);
				if (progress > progressBar.getProgress()) {
					progressBar.setProgress(progress);
				} else {
					progressBar.setProgress(205);
				}
			} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				// head-set plugged
				if (intent.getIntExtra("state", 0) == 0) {
					if(mFMRingState.isChecked()) {
						mFMRingState.setChecked(false);
					}
					mFMRingState.setEnabled(false);
					mFMAlarmPref.setEnabled(false);
					Dialog alarmDialog = mFMAlarmPref.getDialog();
					if(alarmDialog != null && alarmDialog.isShowing()) {
						alarmDialog.dismiss();
					}
					mAlarmPref.setEnabled(true);
				} else {
					mFMRingState.setEnabled(true);
					mFMRingState.setChecked(mOriginalAlarm.fmState);
					if (mFMAlarmPref.mEntries != null) {
						mFMAlarmPref.setEnabled(mOriginalAlarm.fmState);
						mAlarmPref.setEnabled(!mOriginalAlarm.fmState);
					} else {
						mFMAlarmPref.setEnabled(false);
						mAlarmPref.setEnabled(true);
					}
				}
			}
		}
	};


FMAlarmPreference.java文件

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.deskclock;

import net.kindroid.fm.IFMService;

import com.android.deskclock.R;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.ListPreference;
import android.util.AttributeSet;
import android.util.Log;

/**
 * The FMRingtonePreference does not have a way to get/set the current ringtone
 * so we override onSaveRingtone and onRestoreRingtone to get the same behavior.
 */
public class FMAlarmPreference extends ListPreference {
	CharSequence[] mEntries;
	CharSequence[] mEntryValues;
	public static final String NO_SELECTION = "0";
	private int mClickedDialogEntryIndex;
	private Context mContext;
	private int mChannel;
	public boolean first = true;
	public boolean isFMPreferenceFocus = false;

	/**
	 * The content:// style URL for FM channel list table
	 */
	public static final Uri CONTENT_URI = Uri.parse("content://"
			+ "net.kindroid.provider.fm_list" + "/" + "FMTable");

	public FMAlarmPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;
		this.setSummary(R.string.select_channel);
		getDataFromDatabases();
		this.setEntries(mEntries);
		this.setEntryValues(mEntryValues);
		this.setDefaultValue(NO_SELECTION);
		this.setDialogTitle(R.string.fm_channel_list);
	}

	private void getDataFromDatabases() {
		ContentResolver resolver = mContext.getContentResolver();
		String order = "tune ASC";
		Cursor cur = resolver.query(CONTENT_URI, null, null, null, order);

		if (cur != null && cur.getCount() > 0) {
			int count = cur.getCount();
			mEntries = new CharSequence[count];
			mEntryValues = new CharSequence[count];

			cur.moveToFirst();

			for (int i = 0; i < count; i++) {
				String channel = cur.getString(cur
						.getColumnIndexOrThrow("tune"));
				String title = cur
						.getString(cur.getColumnIndexOrThrow("title"));
				mChannel = Integer.parseInt(channel);
				int index = channel.length() - 1;
				channel = channel.substring(0, index) + "."
						+ channel.substring(index);
				mEntries[i] = channel + " MHz";
				if (title == null) {
					title = mContext.getString(R.string.no_title);
				}
				mEntryValues[i] = title;
				cur.moveToNext();
			}
		} else {

			mEntries = null;
			mEntryValues = null;
			return;
		}
	}

	public void updateEntres() {
		getDataFromDatabases();
		this.setEntries(mEntries);
		this.setEntryValues(mEntryValues);
		this.setDefaultValue(NO_SELECTION);
		this.setDialogTitle(R.string.fm_channel_list);
		this.notifyChanged();
	}

	private void closeVoice() {
		Intent closeVolume = new Intent();
		closeVolume.setAction(Intent.ACTION_FM);
		closeVolume.putExtra("state", 0);
		closeVolume.putExtra("speaker", 0);
		mContext.sendBroadcast(closeVolume);
	}
	public void searchChannel() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				int start = 875;
				int sq = 875;
				ContentValues values = null;
				ContentResolver resolver = mContext.getContentResolver();
				closeVoice();
				mContext.startService(new Intent(SetAlarm.FMSERVICE));
				mContext.bindService(new Intent(SetAlarm.FMSERVICE),
						serviceConnection, Context.BIND_AUTO_CREATE);
				try {
					Thread.sleep(500);
				} catch (Exception e) {
				}
				try {
					if (mFMService == null) {
						mContext.bindService(new Intent(SetAlarm.FMSERVICE),
								serviceConnection, Context.BIND_AUTO_CREATE);
						try {
							Thread.sleep(1000);
						} catch (Exception e) {
						}
					}
					if(mFMService != null){
						mFMService.openFM();
						if (mFMService.isOpen()) {
							Intent setProgress = new Intent();
							setProgress.setAction(SetAlarm.SET_PROGRESS);
							while (mFMService.searchStation(start, 1, 0, 0)) {
								// get the search tune
								sq = mFMService.getCurrentFrequency();
								Log.e("autosearch", "sq = " + sq);

								if (sq >= 875 && sq <= 1080) {
									setProgress.putExtra(SetAlarm.PROGRESS,
											sq - 875);
									mContext.sendBroadcast(setProgress);

									String where = "tune = " + sq;
									Cursor cur = null;

									cur = resolver.query(CONTENT_URI, null, where,
											null, null);
									if (cur != null && cur.getCount() < 1) {
										// insert
										values = new ContentValues();
										values.put("tune", sq);
										values.put("title", "");
										values.put("comment", 0);
										resolver.insert(CONTENT_URI, values);
									}
								}
								if (start >= sq) {
									releaseFM();

									break;
								}
								start = sq;
							}
						}
					}
					
				} catch (Exception e) {
				}
				mContext.sendBroadcast(new Intent(SetAlarm.SEARCH_DONE));
			}
		}).start();
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		releaseFM();
		first = true;
		isFMPreferenceFocus = false;
		
		super.onDismiss(dialog);
	}

	@Override
	protected void onPrepareDialogBuilder(Builder builder) {
		super.onPrepareDialogBuilder(builder);
		updateEntres();
		if (mEntries == null || mEntryValues == null) {
			throw new IllegalStateException(
					"ListPreference requires an entries array and an entryValues array.");
		}
		isFMPreferenceFocus = true;
		try
		{
			mContext.bindService(new Intent(SetAlarm.FMSERVICE), serviceConnection, Context.BIND_AUTO_CREATE);
		} catch (Exception e)
		{
		}
		String str = (String) this.getSummary();
		for (int i = 0; i < mEntries.length; i++) {
			if (mEntries[i].equals(str)) {
				mClickedDialogEntryIndex = i;
				break;
			}
		}

		if (str != mContext.getString(R.string.select_channel)) {
			mChannel = (int) (Float.parseFloat(str.substring(0,
					str.lastIndexOf(" "))) * 10);
		}
		builder.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						mClickedDialogEntryIndex = which;

						String str = (String) mEntries[mClickedDialogEntryIndex];
						mChannel = (int) ((Float.parseFloat(str.substring(0,
								str.lastIndexOf(" ")))) * 10);
						try {
							if(first) {
								if(mFMService == null) {
									try
									{
										mContext.bindService(new Intent(SetAlarm.FMSERVICE), serviceConnection, Context.BIND_NOT_FOREGROUND);
									} catch (Exception e)
									{
									}
								}
								if (mFMService != null && !mFMService.isOpen()) {
									mFMService.openFM();
									mFMService.setCurrentFrequency(mChannel);
									setVolume();
								}
								first = false;
							}
							if (mFMService != null) {
								mFMService.setCurrentFrequency(mChannel);
							}
						} catch (RemoteException e) {
						}
					}
				});

		builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String str = Integer.toString(mChannel);
				FMAlarmPreference.this.setSummary(str.substring(0,
						str.length() - 1)
						+ "."
						+ str.substring(str.length() - 1) + " MHz");
				FMAlarmPreference.this.callChangeListener(null);
			}
		});
		builder.setNegativeButton(android.R.string.cancel, null);
	}

	/**
	 * bind FM service
	 */
	public void bindService() {
		if(mFMService == null) {
			try
			{
				mContext.bindService(new Intent(SetAlarm.FMSERVICE), serviceConnection, Context.BIND_AUTO_CREATE);
				first = true;
			} catch (Exception e)
			{
			}
		}
	}

	/**
	 * close FM devices and stop service
	 */
	public void releaseFM() {
		if (mFMService != null) {
			mContext.unbindService(serviceConnection);
			mFMService = null;

			//this will send to FMService
			mContext.sendBroadcast(new Intent("net.kindroid.ALARM_FM_SWITCH"));
		}
	}

	/**
	 * open voice
	 */
	private void openVoice()
	{
		Intent voiceIntent = new Intent();
		voiceIntent.setAction(Intent.ACTION_FM);
		voiceIntent.putExtra("state", 1);
		voiceIntent.putExtra("speaker", 0);
		mContext.sendBroadcast(voiceIntent);
	}

	/**
	 * return the selected channel
	 * 
	 * @return
	 */
	public int getChannel() {
		return mChannel;
	}

	/**
	 * fm service
	 */
	private IFMService mFMService = null;

	/**
	 * fm service connection
	 */
	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mFMService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mFMService = (IFMService) IFMService.Stub.asInterface(service);
		}
	};

	/**
	 * set current fm volume sync with framework
	 */
	private void setVolume() {
		AudioManager am = (AudioManager) mContext
				.getSystemService(Context.AUDIO_SERVICE);
		int fm_volume = am.getStreamVolume(AudioManager.STREAM_FM);
		openVoice();
		try {
			mFMService.setVolume(fm_volume);
		} catch (RemoteException e) {
		}
	}
}


SetAlarm.java

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.deskclock;


import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TimePicker;
import android.widget.Toast;
import android.text.InputFilter;
import android.text.Spanned;

/**
 * Manages each alarm
 */
public class SetAlarm extends PreferenceActivity
        implements TimePickerDialog.OnTimeSetListener,
        Preference.OnPreferenceChangeListener {

    private EditTextPreference mLabel;
    private CheckBoxPreference mEnabledPref;
    private Preference mTimePref;
    private AlarmPreference mAlarmPref;
	private FMAlarmPreference mFMAlarmPref;
	private CheckBoxPreference mFMRingState;
    private CheckBoxPreference mVibratePref;
    private RepeatPreference mRepeatPref;
    private MenuItem mTestAlarmItem;
    private AudioManager localAudioManager;

    private int     mId;
    private int     mHour;
    private int     mMinutes;
    private boolean mTimePickerCancelled;
    private Alarm   mOriginalAlarm;
	static String SEARCH_DONE = "com.android.deskclock.search_done";
	static String SET_PROGRESS = "com.android.deskclock.set_progress";
	static String FMSERVICE = "net.kindroid.aidl.service.IFMService";
	static String PROGRESS = "progress";
	private AlertDialog dialog;
	private ProgressBar progressBar;
	final BroadcastReceiver searchBroadcast = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(SEARCH_DONE)) {
				progressBar.setProgress(205);
				mFMAlarmPref.updateEntres();
				if(mFMAlarmPref.mEntries != null && mFMAlarmPref.mEntries.length > 0)
				{
					mFMAlarmPref.setEnabled(true);
				} else
				{
					mFMAlarmPref.setEnabled(false);
				}
				if(dialog != null && dialog.isShowing())
				{
					dialog.dismiss();
				}
			} else if (action.equals(SET_PROGRESS)) {
				int progress = intent.getIntExtra(PROGRESS, 205);
				if (progress > progressBar.getProgress()) {
					progressBar.setProgress(progress);
				} else {
					progressBar.setProgress(205);
				}
			} else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				// head-set plugged
				if (intent.getIntExtra("state", 0) == 0) {
					if(mFMRingState.isChecked()) {
						mFMRingState.setChecked(false);
					}
					mFMRingState.setEnabled(false);
					mFMAlarmPref.setEnabled(false);
					Dialog alarmDialog = mFMAlarmPref.getDialog();
					if(alarmDialog != null && alarmDialog.isShowing()) {
						alarmDialog.dismiss();
					}
					mAlarmPref.setEnabled(true);
				} else {
					mFMRingState.setEnabled(true);
					mFMRingState.setChecked(mOriginalAlarm.fmState);
					if (mFMAlarmPref.mEntries != null) {
						mFMAlarmPref.setEnabled(mOriginalAlarm.fmState);
						mAlarmPref.setEnabled(!mOriginalAlarm.fmState);
					} else {
						mFMAlarmPref.setEnabled(false);
						mAlarmPref.setEnabled(true);
					}
				}
			}
		}
	};

    private Timer pTimer ;
    private TimerTask pTimerTask ;
    private Handler pHandler ;
    private boolean top_flag ;
    private TimePickerDialog tpd ;

    private Toast sameAlarmToast ;
    private boolean mFlag = false;
    private static final int MAX_LABLE = 150;
    private static final int MAX_LABLE_SEND         = 102;
    private static final int MAX_LABLE_DELAY = 700;
    private Handler mHandler = new Handler(){
  	  public void handleMessage(Message message){
  		  switch(message.what){
  		  	case MAX_LABLE_SEND:
  		  		Toast.makeText(getApplicationContext(),getString(R.string.alarm_lable_too_long),Toast.LENGTH_SHORT)
  		  		.show();
  		  		break;
  		  	default:
  		  		break;

  		  }
  	  }
    };
    /**
     * Set an alarm.  Requires an Alarms.ALARM_ID to be passed in as an
     * extra. FIXME: Pass an Alarm object like every other Activity.
     */
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Override the default content view.
        setContentView(R.layout.set_alarm);

        addPreferencesFromResource(R.xml.alarm_prefs);

		localAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // Get each preference so we can retrieve the value later.
        mLabel = (EditTextPreference) findPreference("label");
        mLabel.getEditText().setFilters(new InputFilter[]{new FilenameLength(MAX_LABLE)}); //add by spreadst modify bug 13250 begin:
        mLabel.setOnPreferenceChangeListener(
                new Preference.OnPreferenceChangeListener() {
                    public boolean onPreferenceChange(Preference p,
                            Object newValue) {
                        String val = (String) newValue;
                        // Set the summary based on the new label.
                        p.setSummary(val);
                        mFlag = false;
                        if (val != null && !val.equals(mLabel.getText())) {
                            // Call through to the generic listener.
                            return SetAlarm.this.onPreferenceChange(p,
                                newValue);
                        }
                        return true;
                    }
                });
        mEnabledPref = (CheckBoxPreference) findPreference("enabled");
        mEnabledPref.setOnPreferenceChangeListener(
                new Preference.OnPreferenceChangeListener() {
                    public boolean onPreferenceChange(Preference p,
                            Object newValue) {
                        // Pop a toast when enabling alarms.
                        //if (!mEnabledPref.isChecked()) {
                        //    popAlarmSetToast(SetAlarm.this, mHour, mMinutes,
                        //        mRepeatPref.getDaysOfWeek());
                        //}
                        return SetAlarm.this.onPreferenceChange(p, newValue);
                    }
                });
        mTimePref = findPreference("time");
        mAlarmPref = (AlarmPreference) findPreference("alarm");
        mAlarmPref.setOnPreferenceChangeListener(this);
        mFMRingState = (CheckBoxPreference) findPreference("fm_state");
		mFMRingState.setOnPreferenceChangeListener(this);
		mFMAlarmPref = (FMAlarmPreference) findPreference("fm_channel");
		mFMAlarmPref.setOnPreferenceChangeListener(this);
        mVibratePref = (CheckBoxPreference) findPreference("vibrate");
        mVibratePref.setOnPreferenceChangeListener(this);
        mRepeatPref = (RepeatPreference) findPreference("setRepeat");
        mRepeatPref.setOnPreferenceChangeListener(this);

        Intent i = getIntent();
        mId = i.getIntExtra(Alarms.ALARM_ID, -1);
        if (Log.LOGV) {
            Log.v("In SetAlarm, alarm id = " + mId);
        }

        Alarm alarm = null;
        if (mId == -1) {
            // No alarm id means create a new alarm.
            alarm = new Alarm();
        } else {
            /* load alarm details from database */
            alarm = Alarms.getAlarm(getContentResolver(), mId);
            // Bad alarm, bail to avoid a NPE.
            if (alarm == null) {
                finish();
                return;
            }
        }
        mOriginalAlarm = alarm;

        updatePrefs(mOriginalAlarm);

        // We have to do this to get the save/cancel buttons to highlight on
        // their own.
        getListView().setItemsCanFocus(true);

        // Attach actions to each button.
        Button b = (Button) findViewById(R.id.alarm_save);
        b.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    //if there is a alarm witch has the same hour and minutes , show timepicker again
                    if(Alarms.isSametimeAlarm(getContentResolver(), mHour, mMinutes,mId)){
                        sameAlarmShow(mHour, mMinutes);
                        return;
                    }
                    saveAlarm();
                   // Save the alarm and pop a toast.
                    if(mEnabledPref.isChecked()){
                    	popAlarmSetToast(SetAlarm.this, mHour, mMinutes, mRepeatPref.getDaysOfWeek());
                    }
                    finish();
                }
        });
        final Button revert = (Button) findViewById(R.id.alarm_revert);
        revert.setEnabled(false);
        revert.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    int newId = mId;
                    updatePrefs(mOriginalAlarm);
                    // "Revert" on a newly created alarm should delete it.
                    /*
                    if (mOriginalAlarm.id == -1) {
                        if(newId!=-1)
                        Alarms.deleteAlarm(SetAlarm.this, newId);
                    } else {
                        saveAlarm();
                    }
                    */
                    revert.setEnabled(false);
                }
        });
        b = (Button) findViewById(R.id.alarm_delete);
        if (mId == -1) {
            b.setEnabled(false);
            mTimePickerCancelled = true;
        } else {
            b.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    deleteAlarm();
                }
            });
        }
        
        // The last thing we do is pop the time picker if this is a new alarm.
        if (mId == -1) {
            // Assume the user hit cancel
            mTimePickerCancelled = true;
            showTimePicker();
        }
        registerReceiver(searchBroadcast, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
     }


    @Override
    protected void onPause(){
      super.onPause() ;
      top_flag = false ;
      mFlag = false;
    }

    private class PickerTimerTask extends TimerTask{
       @Override
       public void run(){
        if(pTimerTask != null){
           pTimerTask.cancel();
           pTimerTask = null ;
          }
        if(pTimer != null){
          pTimer.cancel() ;
          pTimer = null ;
         }
        if( top_flag ){
           Message msg = pHandler.obtainMessage(0);
           msg.sendToTarget();
         }
        }
    }

	@Override
	protected void onResume() {
		mFMAlarmPref.updateEntres();
		if (mFMAlarmPref.mEntries == null) {
			mFMAlarmPref.setEnabled(false);
		}
		if(mFMAlarmPref != null && mFMAlarmPref.isFMPreferenceFocus) {
			mFMAlarmPref.bindService();
		}
		super.onResume();
	}

	@Override
	protected void onStop() {
		mFMAlarmPref.releaseFM();
		mFMAlarmPref.first = true;
		if(dialog != null && dialog.isShowing())
		{
			dialog.dismiss();
			dialog = null;
		}
		super.onStop();
	}

    @Override
	protected void onDestroy() {
		unregisterReceiver(searchBroadcast);
		super.onDestroy();
	}

	// Used to post runnables asynchronously.
    private static final Handler sHandler = new Handler();

    public boolean onPreferenceChange(final Preference p, Object newValue) {
        // Asynchronously save the alarm since this method is called _before_
        // the value of the preference has changed.
        sHandler.post(new Runnable() {
            public void run() {
                // Editing any preference (except enable) enables the alarm.
                if (p != mEnabledPref) {
                    mEnabledPref.setChecked(true);
                }
            final Button revert = (Button) findViewById(R.id.alarm_revert);
            revert.setEnabled(true);
            }
        });
        return true;
    }

    private void updatePrefs(Alarm alarm) {
        mId = alarm.id;
        mEnabledPref.setChecked(alarm.enabled);
        mLabel.setText(alarm.label);
        mLabel.setSummary(alarm.label);
        mHour = alarm.hour;
        mMinutes = alarm.minutes;
        mRepeatPref.setDaysOfWeek(alarm.daysOfWeek);
        mVibratePref.setChecked(alarm.vibrate);
		mFMRingState.setChecked(alarm.fmState);

		if (localAudioManager != null &&  !localAudioManager.isWiredHeadsetOn()) {
			mFMRingState.setEnabled(false);
			mFMAlarmPref.setEnabled(false);
			mAlarmPref.setEnabled(true);
		} else if (mFMAlarmPref.mEntries == null) {
			mFMAlarmPref.setEnabled(false);
			mFMRingState.setEnabled(true);
			if (mFMRingState.isChecked()) {
				searchConfirm();
			}
		} else {
			mFMRingState.setEnabled(true);
			mFMAlarmPref.setEnabled(alarm.fmState);
			mAlarmPref.setEnabled(!alarm.fmState);
		}
        // Give the alert uri to the preference.
        mAlarmPref.setAlert(alarm.alert);
        if (alarm.fmChannel != 0) {
			String str = Integer.toString(alarm.fmChannel);
			mFMAlarmPref.setSummary(str.substring(0, str.length() - 1) + "."
					+ str.substring(str.length() - 1) + " MHz");
		} else {
			mFMAlarmPref.setSummary(getString(R.string.select_channel));
		}
        mAlarmPref.setAlert(alarm.alert , alarm.alert_title);
        updateTime();
    }

	@Override
    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
            Preference preference) {
        if (preference == mTimePref) {
            showTimePicker();
        } else if (preference == mFMRingState) {
			mAlarmPref.setEnabled(!mFMRingState.isChecked());
			mFMAlarmPref.updateEntres();
			if (mFMAlarmPref.mEntries == null) {
				mFMAlarmPref.setEnabled(false);
				if (mFMRingState.isChecked()) {
					searchConfirm();
				}
			} else {
				mFMAlarmPref.setEnabled(mFMRingState.isChecked());
			}
		}

        return super.onPreferenceTreeClick(preferenceScreen, preference);
    }

    @Override
    public void onBackPressed() {
        // In the usual case of viewing an alarm, mTimePickerCancelled is
        // initialized to false. When creating a new alarm, this value is
        // assumed true until the user changes the time.
        /*
        if (!mTimePickerCancelled) {
            saveAlarm();
        }
        */
	//when setting a new alarm,should not save this new alarm
	//if someone want cancel the new alarm eventhough setting changed been listened.
        //and existed clock should not save any alarm setting info before "done" button is click.
        finish();
    }

    private void showTimePicker() {
      if( tpd != null ){
        if( tpd.isShowing() ){
          tpd.cancel() ;
         }
       }

       tpd = new TimePickerDialog(this, this, mHour, mMinutes,
                DateFormat.is24HourFormat(this)) ;
       tpd.show() ;
       mTimePickerCancelled = false;
    }


    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // onTimeSet is called when the user clicks "Set"
        mTimePickerCancelled = false;
      //if there is a alarm witch has the same hour and minutes , show timepicker again
        if(Alarms.isSametimeAlarm(getContentResolver(), hourOfDay, minute,mId)){
            sameAlarmShow(hourOfDay, minute);
            return;
        }
        mHour = hourOfDay;
        mMinutes = minute;
        updateTime();
        // If the time has been changed, enable the alarm.
        mEnabledPref.setChecked(true);
        //popAlarmSetToast(this, saveAlarmAndEnableRevert());
        final Button revert = (Button) findViewById(R.id.alarm_revert);
        revert.setEnabled(true);
    }

    private void updateTime() {
        if (Log.LOGV) {
            Log.v("updateTime " + mId);
        }
        mTimePref.setSummary(Alarms.formatTime(this, mHour, mMinutes,
                mRepeatPref.getDaysOfWeek()));
    }

    private long saveAlarmAndEnableRevert() {
        // Enable "Revert" to go back to the original Alarm.
        long time=saveAlarm();
        final Button revert = (Button) findViewById(R.id.alarm_revert);
        revert.setEnabled(true);
        return time;
    }

    private long saveAlarm() {
        Alarm alarm = new Alarm();
        alarm.id = mId;
        alarm.enabled = mEnabledPref.isChecked();
        alarm.hour = mHour;
        alarm.minutes = mMinutes;
        alarm.daysOfWeek = mRepeatPref.getDaysOfWeek();
        alarm.vibrate = mVibratePref.isChecked();
		alarm.fmState = mFMRingState.isChecked();
		String str = (String) mFMAlarmPref.getSummary();
		if (str != getString(R.string.select_channel)) {
			alarm.fmChannel = (int) (Float.parseFloat(str.substring(0,
					str.lastIndexOf(" "))) * 10);
		} else {
			alarm.fmChannel = mFMAlarmPref.getChannel();
		}
        alarm.label = mLabel.getText();
        alarm.alert = mAlarmPref.getAlert();
        alarm.alert_title = mAlarmPref.getAlertTitle() ;
        long time;
        if (alarm.id == -1) {
            time = Alarms.addAlarm(this, alarm);
            // addAlarm populates the alarm with the new id. Update mId so that
            // changes to other preferences update the new alarm.
            mId = alarm.id;
        } else {
            time = Alarms.setAlarm(this, alarm);
        }
        return time;
    }

    private void deleteAlarm() {
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.delete_alarm))
                .setMessage(getString(R.string.delete_alarm_confirm))
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface d, int w) {
                                Alarms.deleteAlarm(SetAlarm.this, mId);
                                finish();
                            }
                        })
                .setNegativeButton(android.R.string.cancel, null)
                .show();
    }
    
    private void searchConfirm() {
		new AlertDialog.Builder(this)
				.setTitle(getString(R.string.info))
				.setMessage(getString(R.string.auto_search_confirm))
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int w) {
								dialog.dismiss();
								searchProcess();
							}

							private void searchProcess() {
								LinearLayout myLayout;
								LayoutInflater layoutInflater;
								AlertDialog.Builder dialogBuilder;

								myLayout = new LinearLayout(SetAlarm.this);
								layoutInflater=(LayoutInflater) getSystemService(SetAlarm.this.LAYOUT_INFLATER_SERVICE);
								myLayout=(LinearLayout) layoutInflater.inflate(R.layout.progress_dialog, null);

								progressBar=(ProgressBar)myLayout.findViewById(R.id.progressBar);
								progressBar.setMax(205);

								dialogBuilder = new AlertDialog.Builder(SetAlarm.this);
								dialogBuilder.setView(myLayout);
								dialogBuilder.setMessage(SetAlarm.this.getString(R.string.channel_searching));
								dialog = dialogBuilder.show();
								dialog.setCancelable(false);
								if (localAudioManager != null && localAudioManager.isWiredHeadsetOn()) {
									registerReceiver(searchBroadcast, new IntentFilter(SEARCH_DONE));
									registerReceiver(searchBroadcast, new IntentFilter(SET_PROGRESS));
									mFMAlarmPref.searchChannel();
								} else {
									if(dialog != null && dialog.isShowing())
									{
										dialog.dismiss();
									}
									Toast toast = Toast.makeText(SetAlarm.this, SetAlarm.this.getString(R.string.plug_in_headset), Toast.LENGTH_LONG);
									ToastMaster.setToast(toast);
									toast.show();
								}
							}
						})
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								mFMRingState.setChecked(false);
								mAlarmPref.setEnabled(true);
								dialog.dismiss();
							}

						}).show();
	}

    /**
     * Display a toast that tells the user how long until the alarm
     * goes off.  This helps prevent "am/pm" mistakes.
     */
    static void popAlarmSetToast(Context context, int hour, int minute,
                                 Alarm.DaysOfWeek daysOfWeek) {
        popAlarmSetToast(context,
                Alarms.calculateAlarm(hour, minute, daysOfWeek)
                .getTimeInMillis());
    }

    static void popAlarmSetToast(Context context, long timeInMillis) {
        String toastText = formatToast(context, timeInMillis);
        Toast toast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
        ToastMaster.setToast(toast);
        toast.show();
    }

    /**
     * format "Alarm set for 2 days 7 hours and 53 minutes from
     * now"
     */
    static String formatToast(Context context, long timeInMillis) {
        long delta = timeInMillis - System.currentTimeMillis();
        long hours = delta / (1000 * 60 * 60);
        long minutes = delta / (1000 * 60) % 60;
        long days = hours / 24;
        hours = hours % 24;

        String daySeq = (days == 0) ? "" :
                (days == 1) ? context.getString(R.string.day) :
                context.getString(R.string.days, Long.toString(days));

        String minSeq = (minutes == 0) ? "" :
                (minutes == 1) ? context.getString(R.string.minute) :
                context.getString(R.string.minutes, Long.toString(minutes));

        String hourSeq = (hours == 0) ? "" :
                (hours == 1) ? context.getString(R.string.hour) :
                context.getString(R.string.hours, Long.toString(hours));

        boolean dispDays = days > 0;
        boolean dispHour = hours > 0;
        boolean dispMinute = minutes > 0;

        int index = (dispDays ? 1 : 0) |
                    (dispHour ? 2 : 0) |
                    (dispMinute ? 4 : 0);

        String[] formats = context.getResources().getStringArray(R.array.alarm_set);
        return String.format(formats[index], daySeq, hourSeq, minSeq);
    }
    /**
     * when new set time has already been set by other alarms , show timepicker again
     * @param hour
     * @param minute
     */
    private void sameAlarmShow(int hour,int minute){
        String time = hour+":"+minute;
        if(minute<10){
            time = hour+":0"+minute;
        }

        if( sameAlarmToast != null ){
          sameAlarmToast.setText(getString(R.string.alarm_alread_exist, time)) ;
          sameAlarmToast.show() ;
          showTimePicker();
          return ;

        }
        sameAlarmToast = new Toast(this).makeText(this, getString(R.string.alarm_alread_exist, time), Toast.LENGTH_LONG);
        sameAlarmToast.show() ;
        showTimePicker();
    }

    //add by spreadst modify bug 13250 begin:
    public class FilenameLength implements InputFilter {
        public FilenameLength(int max) {
            mMax = max;
        }
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            int keep = mMax - (dest.length() - (dend - dstart));
            if (keep <= 0) {
            	sendFilenameToast(MAX_LABLE_DELAY);
                return "";
            } else if (keep >= end - start) {
                return null; // keep original
            } else {
            	sendFilenameToast(MAX_LABLE_DELAY);
                return source.subSequence(start, start + keep);
            }
        }
        private int mMax;
    }

    public void sendFilenameToast(int delay){
        mHandler.removeMessages(MAX_LABLE_SEND);
        if(mFlag){
        	mHandler.sendEmptyMessageDelayed(MAX_LABLE_SEND, delay);
        }else{
        	mHandler.sendMessage(mHandler.obtainMessage(MAX_LABLE_SEND));
        	mFlag = true;
        }

        }

  //add by spreadst modify bug 13250 end:

}


progress_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_gravity="center_horizontal" 
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
	<ProgressBar 
		android:layout_gravity="center_vertical"
		android:layout_height="wrap_content" 
		android:layout_width="match_parent"
		android:layout_marginTop="10dp"
		android:layout_marginBottom="10dp"
		style="?android:attr/progressBarStyleHorizontal"
		android:id="@+id/progressBar">
	</ProgressBar>
</LinearLayout>


 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值