Android Broadcast receiver gives Error - java

Got another problem. Trying to use a broadcastreceiver to catch off an Alarm (alarm manager).
The following code is used:
package com.suncco.shangxinbao.service;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.suncco.shangxinbao.model.ScheduledSms;
public class SmsTimerService extends BroadcastReceiver {
public SmsTimerService(Context context, int timeoutInSeconds,
ScheduledSms sms) {
Intent myIntent = new Intent(context, SmsTimerService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
sms.getRequestCodeForListener(), myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5); // should be timeoutInSeconds instead of 5
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
Log.w("Karl", "yay");
}
In the manifest I put this as receiver:
<receiver
android:name="com.suncco.shangxinbao.service.SmsTimerService"
android:process=":remote" />
And I make an object of my SmsTimerService like this:
SmsTimerService smsTimerService = new SmsTimerService(this,5,sms);
And this is the well known error...
java.lang.RuntimeException: Unable to instantiate receiver
com.suncco.shangxinbao.service.SmsTimerService: java.lang.InstantiationException:
com.suncco.shangxinbao.service.SmsTimerService

You're getting the unable to instantiate receiver error because you don't have an empty constructor such as SmsTimerService(). The point is you need an empty constructor for this receiver to be created when receiving the intent. And it's ok if you don't implement any constructor. However, if you implement a constructor with parameters, you also need to implement an empty one!
So you can do something like this. Note that I didn't study what you actually want to do when creating intents.
public class SmsTimerService extends BroadcastReceiver {
private void doAction(Context context, int timeoutInSeconds, ScheduledSms sms) {
Intent myIntent = new Intent(context, SmsTimerService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
sms.getRequestCodeForListener(), myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5); // should be timeoutInSeconds instead of
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent) {
// you get to replace sms with something!
doAction(context, 5, sms); // original u do - > new SmsTimerService(this,5,sms);
}
}

Related

Web service call is not working on BroadcastReceiver

package com.example.agniva.demoapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
public class Alarm extends BroadcastReceiver implements PaymentServiceListener {
Database database;
ArrayList<String> log_arrlist;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Log.e("I am in", "Alarm onReceive");
database = new Database(context);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
database.add_log("Alarm !!!!!!!!!!" + "\n");
wl.release();
Cursor cursor = database.getAllLog();
log_arrlist = new ArrayList<>();
if (cursor.moveToFirst()) {
Log.e("Cursor Object>>>>>>>", DatabaseUtils.dumpCursorToString(cursor));
do {
String allLog = cursor.getString(cursor.getColumnIndex("fld_log_name"));
Log.e("allLog", ">>>" + allLog);
log_arrlist.add(allLog);
for (int z = 0; z < log_arrlist.size(); z++) {
Log.e("LOG", "ARRAY>>" + log_arrlist.get(z));
}
// do what ever you want here
} while (cursor.moveToNext());
}
cursor.close();
Intent background = new Intent(context, EmergencyService.class);
context.startService(background);
/** Service Call is not working here */
PaymentService paymentService = new PaymentService(context, log_arrlist);
paymentService.execute();
}
public void setAlarm(Context context) {
Log.e("I am in", "Alarm setAlarm");
/*AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("com.example.agniva.demoapp.START_ALARM");
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);*/
alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent("com.example.agniva.demoapp.START_ALARM");
alarmIntent = PendingIntent.getBroadcast(context, 0, i, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() +
5 * 1000, alarmIntent);
}
#Override
public void onGettingPaymentResponse(String result) {
Log.e("Result", ">>" + result);
}
}
It shows Unable to start receiver com.example.agniva.demoapp.Alarm: java.lang.ClassCastException: android.app.ReceiverRestrictedContext cannot be cast to com.example.agniva.demoapp.PaymentServiceListener
Payment Service don't found the context here. Is it possible to call a web service here? Please give me any suggestion or link if you have. Or is there any other way to call a web service in AlarmManager.
The Context that the Receiver expones is not a common Context as you expect. A Receiver could live even without an Activity or a Service so the Context is NOT yours and neither one of your Classes. I think you cast the Context to PaymentServiceListener but it's illegal. You can use that Context to extract Strings or start/launch Services/Activities/Threads but cannot be casted to one of your Classes.

Notifications didn't show up at specified time

What's wrong with this scrap of code? It should came up with an notification at specified time. I have done some testing and logging, but nothing has changed - notifications has never showed up...
NotificationService.java
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
public class NotificationService extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String link = "http://www.login.lt/apdovanojimai/";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder n = new NotificationCompat.Builder(this)
.setContentTitle("LOGIN 2015")
.setContentText(getResources().getString(R.string.rate_at_login))
.setSmallIcon(R.drawable.logo)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
}
}
setAlarm():
private void setAlarm() {
Intent myIntent = new Intent(this , NotificationService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
Calendar date1 = Calendar.getInstance();
date1.set(2015, 04, 16, 19, 00, 00);
Calendar date2 = Calendar.getInstance();
date2.set(2015, 04, 24, 19, 00, 00);
alarmManager.set(AlarmManager.RTC_WAKEUP, date1.getTimeInMillis(), pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, date2.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000 , pendingIntent);
}
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
setAlarm();
}
Considering setAlarm() method is in YourActivity:
private void setAlarm() {
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(YourActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 23);//set the hour which you want
cal.set(Calendar.MINUTE, 56);// set the minute
cal.set(Calendar.SECOND, 0);// set seconds
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
}
In AlarmReceiver class:
public class AlarmReceiver extends BroadcastReceiver {
Context myContext;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
myContext = context;
showNotification();
}
public void showNotification()
{
String link = "http://www.login.lt/apdovanojimai/";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(link));
PendingIntent pIntent = PendingIntent.getActivity(myContext, 0, intent1, 0);
NotificationCompat.Builder n = new NotificationCompat.Builder(myContext)
.setContentTitle("LOGIN 2015")
.setContentText("hello")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) myContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, n.build());
}
}
Make sure you add this in your manifest file:
<receiver android:name=".AlarmReceiver" />

Off RingtoneManager song android

I have tried many solutions such as-
RingtoneManager.stopPreviousRingtone();
But it comes with an error of -
Cannot make a static reference to the non-static method stopPreviousRingtone() from the type RingtoneManager
MyAlarmService.java
package com.example.getbettersoon;
import android.app.Service;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.widget.Toast;
public class MyAlarmService extends Service {
static Ringtone ringtone;
#Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
//RingtoneManager.stopPreviousRingtone();
ringtone.stop(); // THIS DOES NOT STOP THE RINGTONE
}
#SuppressWarnings("deprecation")
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
Uri alarm = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(getApplicationContext(), alarm);
ringtone.play();
}
}
Alarm.java
package com.example.getbettersoon;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.Ringtone;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class Alarm extends Activity {
String gethours;
int myNum;
private PendingIntent pendingIntent;
public void SetAlarm(View arg0) {
Intent myIntent = new Intent(Alarm.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(Alarm.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10); // test
//TextView tv = (TextView) findViewById(R.id.bthrs);
//tv.setText(myNum);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(Alarm.this, "Start Alarm", Toast.LENGTH_LONG).show();
};
public void OffAlarm(View arg0) {
Intent myIntent = new Intent(Alarm.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(Alarm.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(Alarm.this, "Cancel!", Toast.LENGTH_LONG).show();
};
}
When my button is pressed, the ring tone starts after 10 seconds but when I press the stop button the music doesn't stop. Can anyone help me with it?
I assume you are relying on your service being stopped to stop the ringtone playback. The line:
alarmManager.cancel(pendingIntent);
merely removes the service from being deployed in the future by the AlarmManager and does not stop an active service.
To stop a running service you need to use Context.stopService()
For example:
public void OffAlarm(View arg0){
Intent myIntent = new Intent(Alarm.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(Alarm.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Stops an existing running service
stopService(myIntent);
// Tell the user about what we did.
Toast.makeText(Alarm.this, "Cancel!", Toast.LENGTH_LONG).show();
}
only then will the onDestroy() method be called by the android system and your ringtone stopped.

Android Alarm Not Firing

I am trying to register an alarm with the android alarm manager and cannot seem to figure out why the the alarms aren't firing. I've looked at many examples online and my code seems to be doing the same thing that they suggest but still no success. I am running it on android 4.4 (KitKat)
Here is how I set the alarm:
public void registerAlarm(Context context, int hour, int minute) {
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(
Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReciever.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10000,
alarmIntent);
}
and here is how my receiver for it:
package com.alarm.alarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "recieved", Toast.LENGTH_LONG).show();
}
}
Here is how I declare my receiver in the manifest
<receiver android:name="com.alarm.alarm.AlarmReceiver">
</receiver>
and here is the SET ALARM permission
<uses-permission android:name="com.alarm.permission.SET_ALARM"/>
I have been stuck on this issue for hours. any clarification as to what i might be doing wrong would be greatly appreciated!
You have a typo in Broadcast class name, it should be AlarmReceiver instead of AlarmReciever per your Manifest

Android: AlarmManager sometimes doesn't call BroadcastReceiver

In my app, I've got a BroadcastReceiver, which is called by an AlarmManager. That BroadcastReceiver calls CommonsWare's WakefulIntentservice.
I tested this on my phone, and it appeared that sometimes, my BroadcastReceiver isn't called at all. I'm really confused about what it could be. My BroadcastReceiver and WakefulIntentservice are registerd in the manifest.
This is my code:
In AlarmActivity:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 2);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), savedIntervalAutomaticMilisInt, pendingIntent);
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
finish();
AlarmReceiver:
package com.something.app;
import com.commonsware.cwac.wakeful.WakefulIntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmService.class);
WakefulIntentService.sendWakefulWork(context, i);
}
}
And AlarmService:
package com.something.app;
import android.app.PendingIntent;
import android.content.Intent;
import com.commonsware.cwac.wakeful.WakefulIntentService;
public class AlarmService extends WakefulIntentService {
public AlarmService() {
super("AlarmService");
}
#Override
protected void doWakefulWork(Intent arg0) {
//A looooooooot of stuff
}
Does anyone know why the BroadcastReceiver sometimes isn't called?
EDIT: I heard about setting a BroadcastReceiver which receives onBootCompleted. Is that required?
So, that's the problem: If the device reboots, it sometimes clears the alarm, so you have to reset them in a BroadcastReceiver which receives onBootCompleted

Categories

Resources