Я создал уведомление, чтобы показать выпущенный mov ie и сегодняшнее напоминание. У меня есть метод для повторения тревоги, но уведомление появляется только тогда, когда я включаю тревогу через SwitchPreferences. Здесь я хочу показывать уведомления каждый божий день и каждый мов ie, которые я отпускаю, когда я только один раз установил будильник на «ON». Из моего случая здесь, я должен установить и включить будильник для получения уведомлений, но он должен вызывать уведомления или запрашивать данные, когда вызывается функция onReceive () в классе BroadcastReceiver (). Подводя итог, я просто хочу включить будильник один раз, и тогда метод проверит данные из API, если они соответствуют дате, запрашиваемой каждый день
Вот мой AppCompatPref. java:
public class AppCompatPref extends PreferenceActivity {
private AppCompatDelegate mAppCompatDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
getDelegate().installViewFactory();
getDelegate().onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
}
public ActionBar getSupportActionBar() {
return getDelegate().getSupportActionBar();
}
public void invalidateOptionsMenu() {
getDelegate().invalidateOptionsMenu();
}
private AppCompatDelegate getDelegate() {
if (mAppCompatDelegate == null) {
mAppCompatDelegate = AppCompatDelegate.create(this, null);
}
return mAppCompatDelegate;
}
public void setSupportActionBar(@Nullable Toolbar toolbar) {
getDelegate().setSupportActionBar(toolbar);
}
@Override
public MenuInflater getMenuInflater() {
return getDelegate().getMenuInflater();
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
@Override
public void setContentView(View view) {
getDelegate().setContentView(view);
}
@Override
public void setContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().setContentView(view, params);
}
@Override
public void addContentView(View view, ViewGroup.LayoutParams params) {
getDelegate().addContentView(view, params);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
super.onTitleChanged(title, color);
getDelegate().setTitle(title);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getDelegate().onPostCreate(savedInstanceState);
}
@Override
protected void onPostResume() {
super.onPostResume();
getDelegate().onPostResume();
}
@Override
protected void onStop() {
super.onStop();
getDelegate().onStop();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getDelegate().onConfigurationChanged(newConfig);
}
@Override
protected void onDestroy() {
super.onDestroy();
getDelegate().onDestroy();
}
}
Вот мой MovieDailyReminder:
public class MovieDailyReceiver extends BroadcastReceiver {
private void sendNotification(Context context, String title, String desc, int id) {
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(context, MainActivity.class);
PendingIntent mPendingIntent = PendingIntent.getActivity(context, id, mIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri uriTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentTitle(title)
.setContentText(desc)
.setContentIntent(mPendingIntent)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(uriTone);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mNotificationChannel = new NotificationChannel(
"11001", "NOTIFICATION_CHANNEL_NAME",
NotificationManager.IMPORTANCE_HIGH);
mNotificationChannel.enableLights(true);
mNotificationChannel.setLightColor(Color.YELLOW);
mNotificationChannel.enableVibration(true);
mNotificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setChannelId("11001");
mNotificationManager.createNotificationChannel(mNotificationChannel);
}
mNotificationManager.notify(id, builder.build());
}
private static PendingIntent getPendingIntent(Context context) {
Intent mIntent = new Intent(context, MovieDailyReceiver.class);
return PendingIntent.getBroadcast(context, 1001, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public void setAlarm(Context context) {
cancelAlarm(context);
AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY, 7);
mCalendar.set(Calendar.MINUTE, 0);
mCalendar.set(Calendar.SECOND, 0);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,mCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,getPendingIntent(context));
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,mCalendar.getTimeInMillis(), getPendingIntent(context));
}
Toast.makeText(context, "Daily Notif ON", Toast.LENGTH_SHORT).show();
}
public void cancelAlarm(Context context) {
AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mAlarmManager.cancel(getPendingIntent(context));
Toast.makeText(context, "Daily Notif OFF", Toast.LENGTH_SHORT).show();
}
@Override
public void onReceive(Context context, Intent mIntent) {
sendNotification(context, context.getString(R.string.DailyTitle),
context.getString(R.string.DailyCheck), 1001);
}
}
Вот мой MovieUpcomingReminder :
public class MovieUpcomingReceiver extends BroadcastReceiver {
private static int mNotifId = 2000;
private void sendNotification(Context context, String title, String mDesc, int id, ResultsItem mMovieResult) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Uri uriTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notifications_black_24dp)
.setContentTitle(title)
.setContentText(mDesc)
.setColor(ContextCompat.getColor(context, android.R.color.transparent))
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSound(uriTone);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel("11011",
"NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.YELLOW);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setChannelId("11011");
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(id, builder.build());
}
private static PendingIntent getPendingIntent(Context context) {
Intent intent = new Intent(context, MovieUpcomingReceiver.class);
return PendingIntent.getBroadcast(context, 1011, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}
public void setAlarm(Context context, List<ResultsItem> mMovieResults) {
int delay = 0;
for (ResultsItem movie : mMovieResults) {
cancelAlarm(context);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MovieUpcomingReceiver.class);
intent.putExtra("movietitle", movie.getTitle());
intent.putExtra("movieid", movie.getId());
intent.putExtra("movieposter", movie.getPhoto());
intent.putExtra("moviemDescription", movie.getOverview());
intent.putExtra("moviedate", movie.getReleaseDate());
intent.putExtra("id", mNotifId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
alarmManager.setInexactRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis() + delay,
AlarmManager.INTERVAL_DAY,
pendingIntent
);
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis() + delay, pendingIntent);
}
mNotifId += 1;
delay += 3000;
}
Toast.makeText(context, "Upcoming Notif ON", Toast.LENGTH_SHORT).show();
}
@Override
public void onReceive(Context context, Intent intent) {
String mMovieTitle = intent.getStringExtra("movietitle");
int id = intent.getIntExtra("id", 0);
ResultsItem mMovieResult = new ResultsItem();
String mDesc = context.getString(R.string.todayRelease) + " : " +mMovieTitle;
sendNotification(context, context.getString(R.string.app_name), mDesc, id, mMovieResult);
}
public void cancelAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(getPendingIntent(context));
Toast.makeText(context, "Upcoming Notif OFF", Toast.LENGTH_SHORT).show();
}
}
Вот мои настройки Preff:
public class SettingPref extends AppCompatPref {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public static class MainPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
private RequestQueue mRequestQueue;
List<ResultsItem> mNotifList;
MovieDailyReceiver mMovieDailyReceiver = new MovieDailyReceiver();
MovieUpcomingReceiver mMovieUpcomingReceiver = new MovieUpcomingReceiver();
SwitchPreference mSwitchReminder;
SwitchPreference mSwitchToday;
public class GetMovieTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
getData(strings[0]);
return null;
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
boolean value = (boolean) newValue;
if (key.equals(getString(R.string.todayreminder))) {
if (value) {
mMovieDailyReceiver.setAlarm(getActivity());
} else {
mMovieDailyReceiver.cancelAlarm(getActivity());
}
} else {
if (value) {
setReleaseAlarm();
} else {
mMovieUpcomingReceiver.cancelAlarm(getActivity());
}
}
return true;
}
private void setReleaseAlarm() {
Date today = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String todaysDate = dateFormat.format(today);
MainPreferenceFragment.GetMovieTask getDataAsync = new MainPreferenceFragment.GetMovieTask();
getDataAsync.execute("https://api.themoviedb.org/3/discover/movie?api_key=80077c53d53b7215a6c2f2120d065f81&primary_release_date.gte="+todaysDate+"&primary_release_date.lte="+todaysDate);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
mNotifList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(getActivity());
mSwitchReminder = (SwitchPreference) findPreference(getString(R.string.todayreminder));
mSwitchReminder.setOnPreferenceChangeListener(this);
mSwitchToday = (SwitchPreference) findPreference(getString(R.string.todayRelease));
mSwitchToday.setOnPreferenceChangeListener(this);
Preference myPref = findPreference(getString(R.string.languagesets));
myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
startActivity(new Intent(Settings.ACTION_LOCALE_SETTINGS));
return true;
}
});
}
public void getData(String url) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
final String today = dateFormat.format(date);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
ResultsItem movieItem = new ResultsItem();
movieItem.setTitle(data.getString("title"));
movieItem.setReleaseDate(data.getString("release_date"));
movieItem.setTitle(data.getString("title"));
movieItem.setOverview(data.getString("overview"));
movieItem.setOverview(data.getString("poster_path"));
if (data.getString("release_date").equals(today)) {
mNotifList.add(movieItem);
}
}
mMovieUpcomingReceiver.setAlarm(getActivity(), mNotifList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
}
}