Android BroadcastReceiver behaviour - java

I've got a normal java class (not an Activity) which implements an element of my app including a Notification with 2 actions: the first action fires a PendingIntent launching a brand-new activity while the other broadcasts an intent which will be caught in a Receiver class extending BroadcastReceiver and all goes well (for now is only playing a sound from RAW directory)
Since i need to update particular aspects of the object implemented in the first java class, I put the receiver in my class, extending BroadcastReceiver this way, but the test sound is not played at all. The code in the onReceive method is the same in both classes.
SingleInstance.java
package com.thepier.ingresstimer;
*various imports*
public class SingleInstance extends BroadcastReceiver {
/* Notification Misc */
private int ID;
private NotificationManager nm;
/* App context */
private Context cntx;
/* Contatore */
private int intCounter = 0;
/* Portal Data */
private int hackMax = 4; /* hackMax minimo */
private long coolTime = 300000; /* millisecondi = 5 minuti */
private long burnTime = 14400000; /* millisecondi = 4 ore */
/* Portal Cooldowns */
CountDownTimer cooldownTimer;
CountDownTimer burnoutTimer;
*other code*
public void showNotification () {
Intent intentPref = new Intent(cntx, PreferencesActivity.class);
PendingIntent pIntent1 = PendingIntent.getActivity(cntx, 0, intentPref, 0);
Intent intentHack = new Intent(cntx, SingleInstance.class);
//OR Intent intentHack = new Intent(cntx, HackReceiver.class);
intentHack.putExtra("ID", this.ID);
intentHack.putExtra("maxH", this.hackMax);
intentHack.putExtra("curH", this.intCounter);
PendingIntent pIntent2 = PendingIntent.getBroadcast(cntx, 0, intentHack, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(cntx)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Cooldown terminato")
.setTicker("Cooldown terminato")
.addAction(R.drawable.ic_action_new, "Hack", pIntent2)
.addAction(R.drawable.ic_action_settings, "Impostazioni", pIntent1)
.setContentText("Hack: "+intCounter+"/"+hackMax);
nm.notify(ID, mBuilder.build());
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sfx_portal_hacking_alien);
mediaPlayer.start();
}
}
HackReceiver.java
package com.thepier.ingresstimer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
public class HackReceiver extends BroadcastReceiver {
public HackReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// TODO Auto-generated method stub
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sfx_portal_hacking_alien);
mediaPlayer.start();
}
}

Problem solved: forgot the empty constructor needed by BroadcastReceiver

Related

Java Android Media Player (Notification)

So I have the following code and it is working fine, however I want to show the media controls in the users Notification area so they can play and stop the music as they please while the app is in the background.
I am wondering how one does this?
Code:
package com.radiomedia.a1liferadio;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ImageView imagePlayPause;
private TextView textCurrentTime, textTotalDuration;
private SeekBar playerSeekBar;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePlayPause = findViewById(R.id.imagePlayPause);
textCurrentTime = findViewById(R.id.textCurrentTime);
textTotalDuration = findViewById(R.id.textTotalDuration);
playerSeekBar = findViewById(R.id.playerSeekBar);
mediaPlayer = new MediaPlayer();
playerSeekBar.setMax(100);
imagePlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mediaPlayer.isPlaying())
{
handler.removeCallbacks(updater);
mediaPlayer.pause();
imagePlayPause.setImageResource(R.drawable.ic_play);
}else{
mediaPlayer.start();
imagePlayPause.setImageResource(R.drawable.ic_pause);
updateSeekBar();
}
}
});
prepareMediaPlayer();
}
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource("http://stream.radiomedia.com.au:8003/stream"); //url of media
mediaPlayer.prepare();
textTotalDuration.setText(milliSecondsToTimer(mediaPlayer.getDuration()));
} catch (Exception exception){
Toast.makeText(this,exception.getMessage(), Toast.LENGTH_SHORT).show();
}
};
private Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
long currentDuration = mediaPlayer.getCurrentPosition();
textCurrentTime.setText(milliSecondsToTimer(currentDuration));
}
};
private void updateSeekBar(){
if(mediaPlayer.isPlaying()) {
playerSeekBar.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100));
handler.postDelayed(updater, 1000);
}
};
private String milliSecondsToTimer(long milliSeconds) {
String timerString = "";
String secondsString;
int hours = (int)(milliSeconds / (1000 * 60 * 60));
int minutes = (int)(milliSeconds % (1000 * 60 * 60)) / (1000 *60);
int seconds = (int)((milliSeconds % (1000 * 60 *60)) % (1000 * 60) / 1000);
if(hours > 0)
{
timerString = hours + ":";
}
if(seconds < 10)
{
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;
}
timerString = timerString + minutes + ":" + secondsString;
return timerString;
}
}
You should follow this old google mediaplayer sample (Use this commit if the master version crashes for you) if you want to keep using the MediaPlayer.
But If you don't mind using ExoPlayer, then you should instead follow this new one, since ExoPlayer can already take care of part of the notification stuff.
But so in these sample projects you can see that:
It's not as simple as just a notification, it also ties into people pressing on a play button on their headset etc.
You really need a service for this, to bind to the notification, to handle the action.MEDIA_BUTTON intents.
Minimal code for adding such a notification with a MediaSession and Service with the MediaPlayer (so not ExoPlayer) like you are using would look something like this:
Add the media compat libraries to your apps' build gradle:
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation "androidx.media:media:1.1.0"
}
Then create a class for creating the Notification:
package com.radiomedia.a1liferadio;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.media.app.NotificationCompat.MediaStyle;
import androidx.media.session.MediaButtonReceiver;
/**
* Keeps track of a notification and updates it automatically for a given MediaSession. This is
* required so that the music service don't get killed during playback.
*/
public class MediaNotificationManager {
public static final int NOTIFICATION_ID = 412;
private static final String TAG = MediaNotificationManager.class.getSimpleName();
private static final String CHANNEL_ID = "com.example.android.musicplayer.channel";
private static final int REQUEST_CODE = 501;
private final MediaSessionService mService;
private final NotificationCompat.Action mPlayAction;
private final NotificationCompat.Action mPauseAction;
private final NotificationManager mNotificationManager;
public MediaNotificationManager(MediaSessionService musicContext) {
mService = musicContext;
mNotificationManager =
(NotificationManager) mService.getSystemService(Service.NOTIFICATION_SERVICE);
mPlayAction =
new NotificationCompat.Action(
R.drawable.ic_play,
"play",
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_PLAY));
mPauseAction =
new NotificationCompat.Action(
R.drawable.ic_pause,
"pause",
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_PAUSE));
// Cancel all notifications to handle the case where the Service was killed and
// restarted by the system.
mNotificationManager.cancelAll();
}
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
}
public NotificationManager getNotificationManager() {
return mNotificationManager;
}
public Notification getNotification(MediaMetadataCompat metadata,
#NonNull PlaybackStateCompat state,
MediaSessionCompat.Token token) {
boolean isPlaying = state.getState() == PlaybackStateCompat.STATE_PLAYING;
MediaDescriptionCompat description = metadata.getDescription();
NotificationCompat.Builder builder =
buildNotification(state, token, isPlaying, description);
return builder.build();
}
private NotificationCompat.Builder buildNotification(#NonNull PlaybackStateCompat state,
MediaSessionCompat.Token token,
boolean isPlaying,
MediaDescriptionCompat description) {
// Create the (mandatory) notification channel when running on Android Oreo.
if (isAndroidOOrHigher()) {
createChannel();
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, CHANNEL_ID);
builder.setStyle(
new MediaStyle()
.setMediaSession(token)
.setShowActionsInCompactView(0)
// For backwards compatibility with Android L and earlier.
.setShowCancelButton(true)
.setCancelButtonIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(
mService,
PlaybackStateCompat.ACTION_STOP)))
.setColor(ContextCompat.getColor(mService, R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_play)
// Pending intent that is fired when user clicks on notification.
.setContentIntent(createContentIntent())
// Title - Usually Song name.
.setContentTitle(description.getTitle())
// When notification is deleted (when playback is paused and notification can be
// deleted) fire MediaButtonPendingIntent with ACTION_PAUSE.
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(
mService, PlaybackStateCompat.ACTION_PAUSE));
builder.addAction(isPlaying ? mPauseAction : mPlayAction);
return builder;
}
// Does nothing on versions of Android earlier than O.
#RequiresApi(Build.VERSION_CODES.O)
private void createChannel() {
if (mNotificationManager.getNotificationChannel(CHANNEL_ID) == null) {
// The user-visible name of the channel.
CharSequence name = "MediaSession";
// The user-visible description of the channel.
String description = "MediaSession and MediaPlayer";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(
new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
Log.d(TAG, "createChannel: New channel created");
} else {
Log.d(TAG, "createChannel: Existing channel reused");
}
}
private boolean isAndroidOOrHigher() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
}
private PendingIntent createContentIntent() {
Intent openUI = new Intent(mService, MainActivity.class);
openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
return PendingIntent.getActivity(
mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}
}
Then Create a Service class that handles playback and the notification button presses:
package com.radiomedia.a1liferadio;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.KeyEvent;
import androidx.annotation.Nullable;
public class MediaSessionService extends Service {
public MediaPlayer mediaPlayer;
public static final String TAG = "MediaSessionService";
public static final int NOTIFICATION_ID = 888;
private MediaNotificationManager mMediaNotificationManager;
private MediaSessionCompat mediaSession;
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
mMediaNotificationManager = new MediaNotificationManager(this);
mediaSession = new MediaSessionCompat(this, "SOME_TAG");
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
mediaPlayer.start();
}
#Override
public void onPause() {
mediaPlayer.pause();
}
});
Notification notification =
mMediaNotificationManager.getNotification(
getMetadata(), getState(), mediaSession.getSessionToken());
startForeground(NOTIFICATION_ID, notification);
}
public MediaMetadataCompat getMetadata() {
MediaMetadataCompat.Builder builder = new MediaMetadataCompat.Builder();
builder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "artist");
builder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "title");
builder.putLong(
MediaMetadataCompat.METADATA_KEY_DURATION, mediaPlayer.getDuration()
);
return builder.build();
}
private PlaybackStateCompat getState() {
long actions = mediaPlayer.isPlaying() ? PlaybackStateCompat.ACTION_PAUSE : PlaybackStateCompat.ACTION_PLAY;
int state = mediaPlayer.isPlaying() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
final PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder();
stateBuilder.setActions(actions);
stateBuilder.setState(state,
mediaPlayer.getCurrentPosition(),
1.0f,
SystemClock.elapsedRealtime());
return stateBuilder.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if ("android.intent.action.MEDIA_BUTTON".equals(intent.getAction())) {
KeyEvent keyEvent = (KeyEvent) intent.getExtras().get("android.intent.extra.KEY_EVENT");
if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PAUSE) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Update your manifest for declaring the service and sending the action.MEDIA_BUTTON intent to it.
<service
android:name=".MediaSessionService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</service>
<receiver android:name="androidx.media.session.MediaButtonReceiver">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
This MediaButtonReceiver above is needed for pre-OREO devices, it will forward the event to the service on those platforms.
Then start the service from your main activity.
ContextCompat.startForegroundService(
MainActivity.this.getApplicationContext(),
new Intent(MainActivity.this.getApplicationContext(), MediaSessionService.class));
Things still to do here are making your main activity send actions to your service or the player in the service somehow, updating the notification and service state on a change, but you should be able to get something working with this code and figure out the rest from the google sample code.
There are two scenarios :
First
if you want to play song in background you should have to start a forground service. forground service is with notification .(pass the seekbar position, play pause state, playlist or video url to service).
After you creating custome notification with media controls whatever you want
you have to add a media player to service also pass your parameters like position , play pause state to service player that it play from your previous state of activity player.
on click of notification you have to do same parameters pass to activity .
Second
Start forground service with attaching a player and bind the activity to it, and handle all controls from notification and activity at the same time.
you can pass player controls to notfication in sense of froground service to start and play song in background .
you can use preference or tinydb for best performance in getting parameters to pass in first case.

Service doesn't work properly when device go to sleep mode

I created a simple android app that will send notification every minutes. For that I use Service in this app. Look the Service code bellow.
public class notiService extends Service {
private final static int interval = 1000 * 60;
Handler myHandler;
Runnable myRunable;
MediaPlayer mp;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this,R.raw.noti2);
createRunnable();
startHandler();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
/**
* Destroy Handler and Runnable
*/
myHandler.removeCallbacks(myRunable);
super.onDestroy ();
}
/**
* Runnable method
*/
public void createRunnable(){
myRunable = new Runnable() {
#Override
public void run() {
mp.start();
send_notification("Notification title", "10");
myHandler.postDelayed(this, interval); /* The interval time */
}
};
}
/**
* Handler method
*/
public void startHandler(){
myHandler = new Handler();
myHandler.postDelayed(myRunable, 0);
}
/**
* Notification method
*/
public void send_notification(String title, String min){
intent = new Intent(getApplicationContext(),MainActivity.class);
//intent.putExtra("open_fragment","open_f2");
PendingIntent my_pIntent = PendingIntent.getActivities(notiService.this,0, new Intent[]{intent},0);
Notification mynoti = new Notification.Builder(notiService.this)
.setContentTitle(title)
.setContentText("It will be start after "+min+" minutes.")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(my_pIntent).getNotification();
mynoti.flags = Notification.FLAG_AUTO_CANCEL;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,mynoti);
}
}
It work properly when the app running. But if I close the app and device go to sleep mode, this code don't work properly.
This time it send notification after 10 minutes or more.
I can't understand why it behave like this! How I can fixed this problem?
Thank you for your response.
you are using handler for this. Handler does not work when device goes to sleep . you can see this link for running handler in sleep mode

AlarmReceiver & Notification Method causing crash?

I am currently trying to set up the date picker and time picker to fire out a notification when the time is reached. I have created a method in MainActivity and this is being called from AlarmReceiver. Every time the timer reaches the set amount, the application is crashing and no errors are being shown in logcat.
I know it is something to do with this method being called from AlarmReceiver, i just don't know what the problems is. This method is also currently linked to a button which is working when pressed (buttonStopAlarm) fires a notification when pressed as wanted) so overall the method does work, it's just not working when being called from another class.
Any help would be greatly appreciated! Thank you!
AlarmReceiver
package servicealarmdemo.test2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
MainActivity main = new MainActivity();
#Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
main.addNotification();
}
}
By doing this MainActivity main = new MainActivity(); you are just creating an instance of MainActivity but it will not have it's context mean this which is basically provided when Activity is started by the OS
so move you Notification code in your Receiver and use arg0 as context
public class AlarmReceiver extends BroadcastReceiver {
//MainActivity main = new MainActivity();
Context cxt;
#Override
public void onReceive(Context arg0, Intent arg1) {
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
cxt = arg0;
//main.addNotification();
addNotification();
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(cxt)
.setSmallIcon(R.drawable.icon_transperent)
.setContentTitle("Achieve Alert!")
.setContentText("This is a reminder for your deadline!");
Intent notificationIntent = new Intent(cxt, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(cxt, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)cxt.getSystemService(Context.NOTIFICATION_SERVICE);
builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
manager.notify(0, builder.build());
}
}

Logical Flow of all Intents (PendingIntents) in this app widget snippet

I am learning how to build home screen widget in Android. This code is for an app widget to toggle RingerMode from NORMAL to SILENT and vice-versa.
This works fine but I need a full in-sight of logical flow (i.e which gets initiated when, goes where, does what, dies when) of all the intents in this.
Please help me understand this topic clearer.
package com.dummies.android.silentmodetoggle;
import android.app.Activity;
import android.app.IntentService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
public class AppWidget extends AppWidgetProvider {
public static String tag ="SilentModeToggleWidget";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(tag, "onReceive() first line");
if(intent.getAction()==null)
{
//Do Something
Log.d(tag, "before startService()");
context.startService(new Intent(context, ToggleService.class));
}
else{
super.onReceive(context, intent);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// Do something in specified intervals
context.startService(new Intent(context, ToggleService.class));
}
public static class ToggleService extends IntentService{
public ToggleService(){
super("AppWidget$ToggleService");
Log.d(tag, "In ToggleService construcor");
}
#Override
protected void onHandleIntent(Intent arg0) {
Log.d(tag, "In ToggleService > onHandleIntent");
// TODO Auto-generated method stub
ComponentName cn = new ComponentName(this, AppWidget.class);
AppWidgetManager mgr = AppWidgetManager.getInstance(this);
mgr.updateAppWidget(cn, buildUpdate(this));
}
private RemoteViews buildUpdate(Context context){
RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget);
AudioManager audioManager = (AudioManager)context.getSystemService(Activity.AUDIO_SERVICE);
if(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT){
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_on);
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
else{
updateViews.setImageViewResource(R.id.phoneState, R.drawable.phone_silent);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
Intent i = new Intent(this, AppWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
return updateViews;
}
}
}
still not sure on what are u asking, but I'll try to answer, if not what u want, please explain in a different way.
Intent are usually started immediatly. You create an Intent can start it by calling startService or startActivity, so for example:
context.startService(new Intent(context, ToggleService.class));
on both times you wrote the above code, the service ToggleService is immediatly started.
PendingIntent on the other hand are saved to be started at later time, so for example
updateViews.setOnClickPendingIntent(R.id.phoneState, pi);
on the above line, the AppWidget Broadcast is started when the user clicks on R.id.phoneState in your HomeScreen AppWidget.
Each PendingIntent is stored in the system with a certain ID, this ID is the requestCode parameter (you used zero on your code)... that means, that if you create a different PendingIntent with the same ID it will override it, meaning a different action will be started when the user clicks on R.id.phoneState

AlarmManager doesn't start my Receiver

I am setting an AlarmaManager event, but my BroadcastReceiver doesn't catch it:
String task_uuid = UUID_Generator.getUUID();
Intent task_intent = new Intent(getApplicationContext(),AlarmReciever.class);
task_intent.putExtra("task_id", task_uuid);
task_intent.putExtra("test", 10101010);
PendingIntent operation =
PendingIntent.getActivity(getBaseContext(),0, task_intent, 0);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
long alarm_time = dateTime.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
AlarmReceiver:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
System.out.println("test!!!");
try {
SMSUtills.sendSMS("0504235325", "נסיון תזמון");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Add this:
startActivity(task_intent);
I have used this code in my project it's work fine:
Intent myIntent1 = new Intent(PrayerTimeActivity.this, AlarmReceiverFri.class);
AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(PrayerTimeActivity.this,0, myIntent1, 0);
alarmManager1.set(AlarmManager.RTC_WAKEUP,Calendar_Object.getTimeInMillis(), pendingIntent1);
and the receiver class is:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiverFri extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// When our Alaram time is triggered , this method will be excuted (onReceive)
// We're invoking a service in this method which shows Notification to the User
Intent myIntent = new Intent(context, NotificationServiceFri.class);
context.startService(myIntent);
}
}
and in AndroidManifest.xml also contain
<receiver android:name=".AlarmReceiverFri" />
Thanks!!!
If my answer will help you then don't forget to accept this answer. :)
My problem is that I didn't specify wake lock permission in my manifast.

Categories