Java tutorial
/* * Copyright (c) 2016 <kaku201313@163.com | 3772304@qq.com> * * 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.kaku.weac.fragment; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlarmManager; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable; import android.support.v4.app.NotificationManagerCompat; import android.support.v7.app.NotificationCompat; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ProgressBar; import android.widget.TextView; import com.kaku.weac.Listener.HttpCallbackListener; import com.kaku.weac.R; import com.kaku.weac.activities.AlarmClockNapNotificationActivity; import com.kaku.weac.bean.AlarmClock; import com.kaku.weac.bean.WeatherDaysForecast; import com.kaku.weac.bean.WeatherInfo; import com.kaku.weac.bean.WeatherLifeIndex; import com.kaku.weac.broadcast.AlarmClockBroadcast; import com.kaku.weac.common.WeacConstants; import com.kaku.weac.common.WeacStatus; import com.kaku.weac.util.AudioPlayer; import com.kaku.weac.util.HttpUtil; import com.kaku.weac.util.LogUtil; import com.kaku.weac.util.MyUtil; import com.kaku.weac.util.WeatherUtil; import com.kaku.weac.view.MySlidingView; import java.io.ByteArrayInputStream; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; /** * ??Fragment * * @author * @version 1.0 2015/06/25 */ public class AlarmClockOntimeFragment extends BaseFragment implements OnClickListener { /** * Log tag AlarmClockOntimeFragment */ private static final String LOG_TAG = "AlarmClockOntimeFragment"; /** * ? */ private TextView mTimeTv; /** * */ private AlarmClock mAlarmClock; /** * ?flag */ private boolean mIsRun = true; /** * */ private static final int UPDATE_TIME = 1; /** * ?? */ private NotificationManagerCompat mNotificationManager; /** * ?? */ private int mNapInterval; /** * ?? */ private int mNapTimes; /** * ? */ private boolean mIsOnclick = false; /** * ?? */ private int mNapTimesRan; /** * ? */ private AudioManager mAudioManager; /** * ?? */ private int mCurrentVolume; /** * ?Handler */ private ShowTimeHandler mShowTimeHandler; private ViewGroup mWeatherInfoGroup; private ProgressBar mWeatherPbar; private TextView mWeatherTypeTv; private TextView mUmbrellaTv; private String mCurrentTimeDisplay = ""; /** * ? */ static class ShowTimeHandler extends Handler { private WeakReference<AlarmClockOntimeFragment> mWeakReference; public ShowTimeHandler(AlarmClockOntimeFragment alarmClockOntimeFragment) { mWeakReference = new WeakReference<>(alarmClockOntimeFragment); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); AlarmClockOntimeFragment alarmClockOntimeFragment = mWeakReference.get(); switch (msg.what) { case UPDATE_TIME: alarmClockOntimeFragment.mTimeTv.setText(msg.obj.toString()); alarmClockOntimeFragment.mCurrentTimeDisplay = alarmClockOntimeFragment.mTimeTv.getText() .toString(); break; } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LogUtil.d(LOG_TAG, getActivity().toString() + "onCreate"); // ?Activity1 WeacStatus.sActivityNumber++; // ???,, getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mAlarmClock = getActivity().getIntent().getParcelableExtra(WeacConstants.ALARM_CLOCK); // ??? mNapInterval = mAlarmClock.getNapInterval(); // ??? mNapTimes = mAlarmClock.getNapTimes(); // XXX:?? // mNapTimes = 1000; // ?? mNapTimesRan = getActivity().getIntent().getIntExtra(WeacConstants.NAP_RAN_TIMES, 0); // playRing(); mNotificationManager = NotificationManagerCompat.from(getActivity()); // ?? mNotificationManager.cancel(mAlarmClock.getId()); mShowTimeHandler = new ShowTimeHandler(this); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { LogUtil.d(LOG_TAG, getActivity().toString() + "onCreateView"); View view = inflater.inflate(R.layout.fm_alarm_clock_ontime, container, false); mTimeTv = (TextView) view.findViewById(R.id.ontime_time); // mTimeTv.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date())); mCurrentTimeDisplay = mTimeTv.getText().toString(); // ? new Thread(new TimeUpdateThread()).start(); // TextView tagTv = (TextView) view.findViewById(R.id.ontime_tag); tagTv.setText(mAlarmClock.getTag()); // ?? TextView napTv = (TextView) view.findViewById(R.id.ontime_nap); // ???? if (mAlarmClock.isNap()) { // X??????? if (mNapTimesRan != mNapTimes) { // ?? napTv.setText(String.format(getString(R.string.touch_here_nap), mNapInterval)); napTv.setOnClickListener(this); } else { napTv.setVisibility(View.GONE); } } else { napTv.setVisibility(View.GONE); } LogUtil.i(LOG_TAG, "??" + mNapTimes); // ?? TextView slidingTipIv = (TextView) view.findViewById(R.id.sliding_tip_tv); final AnimationDrawable animationDrawable = (AnimationDrawable) slidingTipIv.getCompoundDrawables()[0]; // ?4.0 slidingTipIv.post(new Runnable() { @Override public void run() { animationDrawable.start(); } }); MySlidingView mySlidingView = (MySlidingView) view.findViewById(R.id.my_sliding_view); mySlidingView.setSlidingTipListener(new MySlidingView.SlidingTipListener() { @Override public void onSlidFinish() { // ? finishActivity(); } }); // ?? if (mAlarmClock.isWeaPrompt()) { mWeatherInfoGroup = (ViewGroup) view.findViewById(R.id.weather_info_group); mWeatherPbar = (ProgressBar) view.findViewById(R.id.progress_bar); mWeatherTypeTv = (TextView) view.findViewById(R.id.weather_type_tv); mUmbrellaTv = (TextView) view.findViewById(R.id.umbrella_tv); // ? initWeather(); } return view; } private void initWeather() { // ?? if (!MyUtil.isNetworkAvailable(getActivity())) { return; } SharedPreferences share = getActivity().getSharedPreferences(WeacConstants.EXTRA_WEAC_SHARE, Activity.MODE_PRIVATE); // ? String weatherCode = share.getString(WeacConstants.DEFAULT_WEATHER_CODE, getString(R.string.auto_location)); String cityName; String address; // ? if (weatherCode.equals(getString(R.string.auto_location))) { cityName = share.getString(WeacConstants.DEFAULT_CITY_NAME, null); address = null; } else { cityName = null; address = getString(R.string.address_weather, weatherCode); } mWeatherPbar.setVisibility(View.VISIBLE); HttpUtil.sendHttpRequest(address, cityName, new HttpCallbackListener() { @Override public void onFinish(String response) { try { if (!response.contains("error")) { WeatherInfo weatherInfo = WeatherUtil .handleWeatherResponse(new ByteArrayInputStream(response.getBytes())); getActivity().runOnUiThread(new SetWeatherInfoRunnable(weatherInfo)); // ??? } else { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWeatherPbar.setVisibility(View.GONE); } }); } } catch (Exception e) { LogUtil.e(LOG_TAG, "initWeather(): " + e.toString()); } } @Override public void onError(final Exception e) { try { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWeatherPbar.setVisibility(View.GONE); } }); } catch (Exception e1) { LogUtil.e(LOG_TAG, e1.toString()); } } }); } private class SetWeatherInfoRunnable implements Runnable { private WeatherInfo mWeatherInfo; public SetWeatherInfoRunnable(WeatherInfo weatherInfo) { mWeatherInfo = weatherInfo; } @Override public void run() { if (mWeatherInfo == null) { mWeatherPbar.setVisibility(View.GONE); return; } try { Calendar calendar = Calendar.getInstance(); // ? int hour = calendar.get(Calendar.HOUR_OF_DAY); // ?? TextView cityName = (TextView) getActivity().findViewById(R.id.city_name_tv); cityName.setText(mWeatherInfo.getCity()); // ? List<WeatherDaysForecast> weatherDaysForecasts = mWeatherInfo.getWeatherDaysForecast(); /* if (weatherDaysForecasts.size() < 6) { mWeatherPbar.setVisibility(View.GONE); return; }*/ // ? WeatherDaysForecast weather; String time[] = mWeatherInfo.getUpdateTime().split(":"); int hour1 = Integer.parseInt(time[0]); int minute1 = Integer.parseInt(time[1]); //23450520??5?? if ((hour1 == 23 && minute1 >= 45) || (hour1 < 5) || ((hour1 == 5) && (minute1 < 20)) || hour <= 5) { weather = weatherDaysForecasts.get(2); } else { weather = weatherDaysForecasts.get(1); } // id int weatherId; // ? // ? if (hour >= 0 && hour < 6) { weatherId = MyUtil.getWeatherTypeImageID(weather.getTypeDay(), false); // ? } else if (hour >= 6 && hour < 18) { weatherId = MyUtil.getWeatherTypeImageID(weather.getTypeDay(), true); // ? } else { weatherId = MyUtil.getWeatherTypeImageID(weather.getTypeNight(), false); } @SuppressWarnings("deprecation") Drawable drawable = getResources().getDrawable(weatherId); if (drawable != null) { drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); // mWeatherTypeTv.setCompoundDrawables(drawable, null, null, null); } String type = MyUtil.getWeatherType(getActivity(), weather.getTypeDay(), weather.getTypeNight()); String tempHigh = weather.getHigh().replace("", "").substring(3); String tempLow = weather.getLow().replace("", "").substring(3); mWeatherTypeTv.setText(String.format(getString(R.string.weather_type), type, tempHigh, tempLow)); // ? List<WeatherLifeIndex> weatherLifeIndexes = mWeatherInfo.getWeatherLifeIndex(); for (WeatherLifeIndex index : weatherLifeIndexes) { if (index.getIndexName().equals("")) { if (index.getIndexValue().equals("")) { mUmbrellaTv.setVisibility(View.VISIBLE); } } } mWeatherInfoGroup.setVisibility(View.VISIBLE); } catch (Exception e) { LogUtil.e(LOG_TAG, e.toString()); } finally { mWeatherPbar.setVisibility(View.GONE); } } } @Override public void onStop() { super.onStop(); // LogUtil.d(LOG_TAG, getActivity().toString() + "onStop"); // ?????Activity // ?Intent.FLAG_ACTIVITY_CLEAR_TOPflag ?Activity? // ?Intent.FLAG_ACTIVITY_NEW_TASK flag? // ??Activity?????? // LogUtil.d(LOG_TAG, getActivity().toString() + "activityNumber: " // + WeacStatus.sActivityNumber); // ??????onStop() // // if (mIsOnclick) { // // ????Activity?1 // WeacStatus.activityNumber--; // return; // } // // Activity? // if (WeacStatus.activityNumber > 1) { // WeacStatus.activityNumber--; // // // ?? // // mIsRun = false; // // // ?? // // nap(); // // } } @Override public void onDestroy() { LogUtil.d(LOG_TAG, getActivity().toString() + "onDestroy"); super.onDestroy(); // ?? mIsRun = false; // ?????? if (!mIsOnclick) { // ?? nap(); } // ??Activity if (WeacStatus.sActivityNumber <= 1) { // ? AudioPlayer.getInstance(getActivity()).stop(); } // ?Activity? WeacStatus.sActivityNumber--; // If null, all callbacks and messages will be removed. if (mShowTimeHandler != null) { mShowTimeHandler.removeCallbacksAndMessages(null); } // ?? mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mCurrentVolume, AudioManager.ADJUST_SAME); } @Override public void onClick(View v) { switch (v.getId()) { // ?? case R.id.ontime_nap: // ??? onClickNapButton(); break; } } /** * ??Activity? */ private void finishActivity() { // mIsOnclick = true; getActivity().finish(); getActivity().overridePendingTransition(0, 0); } /** * ?? */ private void onClickNapButton() { if (!(mNapTimesRan == mNapTimes)) { // ?? nap(); } // ? finishActivity(); } /** * ?? */ @TargetApi(19) private void nap() { // ??X if (mNapTimesRan == mNapTimes) { return; } // ??1 mNapTimesRan++; LogUtil.d(LOG_TAG, "??" + mNapTimesRan); // ??? Intent intent = new Intent(getActivity(), AlarmClockBroadcast.class); intent.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock); intent.putExtra(WeacConstants.NAP_RAN_TIMES, mNapTimesRan); PendingIntent pi = PendingIntent.getBroadcast(getActivity(), -mAlarmClock.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Activity.ALARM_SERVICE); // XXX // ? long nextTime = System.currentTimeMillis() + 1000 * 60 * mNapInterval; LogUtil.i(LOG_TAG, "??:" + mNapInterval + ""); // ?194.4 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextTime, pi); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, nextTime, pi); } // ? Intent it = new Intent(getActivity(), AlarmClockNapNotificationActivity.class); it.putExtra(WeacConstants.ALARM_CLOCK, mAlarmClock); // FLAG_UPDATE_CURRENT ??? // FLAG_ONE_SHOT ?? PendingIntent napCancel = PendingIntent.getActivity(getActivity(), mAlarmClock.getId(), it, PendingIntent.FLAG_CANCEL_CURRENT); // CharSequence time = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(nextTime); // NotificationCompat.Builder builder = new NotificationCompat.Builder(getActivity()); // PendingIntent Notification notification = builder.setContentIntent(napCancel) // ? .setDeleteIntent(napCancel) // .setContentTitle(String.format(getString(R.string.xx_naping), mAlarmClock.getTag())) // .setContentText(String.format(getString(R.string.nap_to), time)) // ??? .setTicker(String.format(getString(R.string.nap_time), mNapInterval)) // ??? .setSmallIcon(R.drawable.ic_nap_notification) // .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .setAutoCancel(true) // ?? .setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.FLAG_SHOW_LIGHTS).build(); /* notification.defaults |= Notification.DEFAULT_LIGHTS; notification.flags |= Notification.FLAG_SHOW_LIGHTS;*/ // ??? mNotificationManager.notify(mAlarmClock.getId(), notification); } /** * */ private void playRing() { mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); // ? mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAlarmClock.getVolume(), AudioManager.ADJUST_SAME); // if (mAlarmClock.getRingUrl().equals(WeacConstants.DEFAULT_RING_URL) || TextUtils.isEmpty(mAlarmClock.getRingUrl())) { // ? if (mAlarmClock.isVibrate()) { // AudioPlayer.getInstance(getActivity()).playRaw(R.raw.ring_weac_alarm_clock_default, true, true); } else { AudioPlayer.getInstance(getActivity()).playRaw(R.raw.ring_weac_alarm_clock_default, true, false); } // } else if (mAlarmClock.getRingUrl().equals(WeacConstants.NO_RING_URL)) { // ? if (mAlarmClock.isVibrate()) { AudioPlayer.getInstance(getActivity()).stop(); AudioPlayer.getInstance(getActivity()).vibrate(); } else { AudioPlayer.getInstance(getActivity()).stop(); } } else { // ? if (mAlarmClock.isVibrate()) { AudioPlayer.getInstance(getActivity()).play(mAlarmClock.getRingUrl(), true, true); } else { AudioPlayer.getInstance(getActivity()).play(mAlarmClock.getRingUrl(), true, false); } } } /** * */ private class TimeUpdateThread implements Runnable { /** * ? */ private int startedTime = 0; /** * 3 */ private static final int TIME = 60 * 3; @Override public void run() { // Activity? while (mIsRun) { LogUtil.d(LOG_TAG, "TimeUpdateThread(?): " + startedTime); try { // ?XX?Activity??? if (startedTime == TIME) { // ???? if (mAlarmClock.isNap()) { if (!getActivity().isFinishing()) { onClickNapButton(); return; } else { LogUtil.w(LOG_TAG, "????Finishing?"); return; } } else { // ? finishActivity(); } } Thread.sleep(1000); startedTime++; // ? CharSequence currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()) .format(System.currentTimeMillis()); if (mCurrentTimeDisplay.equals(currentTime)) { continue; } Message msg = mShowTimeHandler.obtainMessage(UPDATE_TIME, currentTime); // ??? mShowTimeHandler.sendMessage(msg); } catch (InterruptedException | NullPointerException e) { LogUtil.e(LOG_TAG, "run" + e.toString()); } } } } }