I a trying to get a notifcation to fire at a specific time. I am using AlarmManager and BroadcastReceiver for this.In main activity AlarmManager calls the BroadcastReceiver but I cannot get the notification to fire from that class. It is giving me an error in the line
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
I don't know what to do.
Here's my code
MainActivity
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
long current_time=System.currentTimeMillis();
Calendar time9=Calendar.getInstance();
time9.set(Calendar.HOUR_OF_DAY,16);
time9.set(Calendar.MINUTE,30);
time9.set(Calendar.SECOND,0);
Intent intent=new Intent(MainActivity.this,ScheduledReciever.class);
PendingIntent pintent=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,time9.getTimeInMillis(), interval, pintent);
finish();
}}`
BroadcastReciever
`public class ScheduledReciever extends BroadcastReceiver {
static final int uniqueId=1234;
NotificationManager nm;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
String body="i hope this works";
String title="trying";
Intent it=new Intent(context,SecondActivity.class);
PendingIntent pit=PendingIntent.getActivity(context, 0, it,0);
Notification n=new Notification(R.drawable.att,body,System.currentTimeMillis());
n.setLatestEventInfo(context, title, body, pit);
n.defaults=Notification.DEFAULT_ALL;
nm.notify(uniqueId, n);
}
}
Use the context passed:
nm=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
instead of:
nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Related
I have written some related code for AlarmManager App.
I want to do something like writting a Toast massage in the activity, for sure i can not do that in onReceive() method the question is that how can i do it in the activity?
public class MainActivity extends AppCompatActivity implements View.OnClickListener,BroadConnect.IsConnect {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vv();
setRecurringAlarm(MainActivity.this);
}
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
//updateTime.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
updateTime.setTimeZone(java.util.TimeZone.getTimeZone("GMT+5:00"));
updateTime.set(Calendar.HOUR_OF_DAY,10);
//updateTime.set(Calendar.MINUTE,31);
updateTime.set(Calendar.MINUTE,1);
updateTime.set(Calendar.SECOND,20);
Intent intent = new Intent(context, BroadConnect.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringDownload);
}
#Override
public void onReceiveTimer() {
Toast.makeText(MainActivity.this,"OK",Toast.LENGTH_LONG).show(); //This will not be displayed
}
}
public class BroadConnect extends BroadcastReceiver {
private IsConnect isConnect;
public interface IsConnect{
void onReceiveTimer();
}
public void setIsConnect(IsConnect isConnect) {
this.isConnect = isConnect;
}
#Override
public void onReceive(Context context, Intent intent) {
isConnect.onReceiveTimer(); //It runs this and makes a ERRORE
}
}
My Scenario is to show Greeting notification to my users even they are not using the app. Below code is working fine if the open is opened or minimized. But, I want to show the notification in morning even though the user did not open the application.
Main Activity:
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} //end onCreate
}
My Receiver Class:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
try{
Utils.generateNotification(context);
}catch(Exception e){
e.printStackTrace();
}
}
}
Utils Class:
public class Utils {
public static NotificationManager mManager;
#SuppressWarnings("static-access")
public static void generateNotification(Context context){
mManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent intent1 = new Intent(context,MainActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(context,0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
}
My Alarm Service:
public class MyAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Next Activity:
public class NextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
A few things you need to do here. If the user force closes the app, you need to ensure that you start your service with START_STICKY so that the service restarts when the app is force closed.
In order to get the Service to start when the user has rebooted their phone, you will need your BroadcastReceiver to receive BOOT_COMPLETED which will then start the service.
Your service will then set the Alarm as per normal. You will need to store the time of the alarm you want to set somewhere. I use SharedPrefs (PreferenceManager.getDefaultSharedPreferences(getApplicationContext());) but I'm sure there are better methods.
public class myserveclass extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
.
public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
}
}
}
public void schedueService() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
1000 * 10, pintent);
}
}
this is my code for start service and stop service am able to start service when app is connected with internet and stop when internet is off but after 10 second again service becomes start please check my issue where am doing wrong i have used alarm manger please check please suggest me where am doing wrong .
You need to CANCEL the alarm to stop the service
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pintent);
Hope it helps ツ
I am new to android. I was playing with the AlarmManager and had successufully go a piece of code running with the BroadcastReceiver as a separate class.
I am now trying to put the BroadcastReceiver as inner class but have no luck on firing the BroadcastReceiver. I had no idea what might have gone wrong after hours looking at the code...
Here is my code:
public class InnerService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(InnerBroadcastReceiver.class.toString());
Log.d("InnerService","InnerService starts!");
Log.d("InnerService","class : "+InnerBroadcastReceiver.class.toString());
this.registerReceiver(new InnerBroadcastReceiver(), filter);
scheduleTestAlarmReceiver(this);
}
public static void scheduleTestAlarmReceiver(Context context) {
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver start");
Intent receiverIntent = new Intent(context, InnerBroadcastReceiver.class);
receiverIntent.setAction("com.example.alarmmanagertest.InnerService$InnerBroadcastReceiver");
PendingIntent sender = PendingIntent.getBroadcast(context, 123456789,
receiverIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 1000, sender);
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver complete");
}
private class InnerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("InnerBroadcastReceiver","InnerBroadcastReceiver ALARM Manager fires success!");
}
}
}
It looks like the AlarmManager tried to fire the BroadcastReceiver every second but failed
Logcat:
V/AlarmManager(2439): waitForAlarm result :4
V/AlarmManager(2439): trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
UPDATE
I have tried to change the code for creating intent in onCreate() and scheduleTestAlarmReceiver() to intent = new intent("action_string") and it works. It seems that intent.setAction() is not working.
What will be the pros and cons for creating intent with and without context (Intent(Context packageContext, Class<?> cls) and Intent(String action))?
But I would still like to know why the above code failed. Can anyone explain?
True, it works!
Small changes in my code. Apk with AsyncTask (downloading file from web and parsing it). "OneMeeting" is my class from project.
public class MainActivity extends AppCompatActivity {
public static final String INPUT_FILE_URL = "https://.../";
private RecyclerView recyclerView;
private String getFilesDir;
private ArrayList<OneMeeting> meetingsArr = new ArrayList<>();
private BroadcastReceiver receiver;
private RefreshFile refreshFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getFilesDir = getFilesDir().getAbsolutePath();
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
meetingsArr.add(new OneMeeting("Launching..." , "", "", ""));
recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));
Intent alarmIntent = new Intent("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 111, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 5, pendingIntent);
}
#Override
protected void onResume() {
super.onResume();
refreshFile = new RefreshFile();
IntentFilter filter = new IntentFilter("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
this.registerReceiver(refreshFile, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(refreshFile);
}
private class RefreshFile extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Refresh", Toast.LENGTH_LONG).show();
ParsePage refreshParsingPage = new ParsePage(new ParsePage.OnTaskCompletedListener() {
#Override
public void onTaskCompletedListener(ArrayList<OneMeeting> parsingResultArr) {
meetingsArr = parsingResultArr;
recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));
}
});
refreshParsingPage.execute(getFilesDir);
}
}
}
I have a collection of reminders in my database(sort by time). When my application starts I call setAlarm. I need to add code in onReceive method in order to do these tasks:
Get first reminder from my database
Get the delay associated to the reminder
Schedule a new Alarm for getting the next reminder.
I created a simple BroadcastReceiver class:
public class AlarmReceiver extends BroadcastReceiver{
private static final String DEBUG_TAG= "AlarmReceiver";
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d(DEBUG_TAG,"ALARM!!!");
// --mycode--
}
}
and the Activity class:
public class AlarmActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
context = getApplicationContext();
}
public void setAlarm(View v){
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ Delay,pendingIntent);
Log.i("SETTER","Alarm started");
}
public void stopAlarm(View v){
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
pendingIntent.cancel();
}
}
Now, I would that in the --mycode-- section new Delay is taken (if exists) from database and new Alarm is setted with this new Delay.
How can I set a new AlarmManager from onReceive method?
You can get AlarmManager in the broadcast receiver by accessing it from the context
AlarmManager alarmManager = (AlarmManager)arg0.getSystemService(Context.ALARM_SERVICE);
where arg0 is your context variable