我有一个简单的应用程序,其中一个活动应该在特定时间每天显示通知。 这些是我的课程:
onAlarmReceiver
public class OnAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, AppService.class));
}
}
onBootReceiver
public class OnBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmController alarm = new AlarmController(context);
alarm.StartAlarm();
}
}
AppService发出通知
public class AppService extends Service {
private static String TAG = "AppService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "start job");
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
} else{
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher) // notification icon
.setContentTitle("اtitle") // title for notification
.setContentText("content") // message for notification
.setAutoCancel(true)
.setSound(uri); // clear notification after click
Intent intentt = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intentt,Intent.FLAG_ACTIVITY_CLEAR_TOP);
mBuilder.setContentIntent(pi);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
//
Log.i(TAG, "stop job");
return START_STICKY;
}
}
包含我的闹钟管理器的AlarmController类
public class AlarmController {
private Context m_Context;
private AlarmManager mgr;
private PendingIntent pi;
public AlarmController(Context context) {
m_Context = context;
}
public void StartAlarm() {
mgr = (AlarmManager)m_Context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(m_Context, OnAlarmReceiver.class);
pi=PendingIntent.getBroadcast(m_Context,0 ,i, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 40);
Log.i("AlarmController", "StartAlarm");
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pi);
}
}
我在MainActivity的onCreate方法中写了这个
AlarmController alarm = new AlarmController(this);
alarm.StartAlarm();
甚至将此代码放在一个方法中,以便在第一次安装应用程序时运行。 但它仍会显示通知,几乎每30分钟而不是每天。
我该怎么办?我的代码有什么问题? 谢谢!
答案 0 :(得分:0)
你的类AlarmController必须扩展BroadcastReceiver