Well, i am an Android newbie. I am trying to write an application which has one activity which starts another activity (Preference Activity), and one BoradcastReceiver. They are all in three different files. My question is: How to share Preferences betweens these components, e.g. how to read preferences that are set in Preference Activity from Broadcast Receiver?
I have asked this same exact question before and here is the code I used:
public class BootupReceiver extends BroadcastReceiver {
private static final boolean BOOTUP_TRUE = true;
private static final String BOOTUP_KEY = "bootup";
#Override
public void onReceive(Context context, Intent intent) {
if(getBootup(context)) {
NotificationManager NotifyM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification Notify = new Notification(R.drawable.n,
"NSettings Enabled", System.currentTimeMillis());
Notify.flags |= Notification.FLAG_NO_CLEAR;
Notify.flags |= Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
Notify.contentView = contentView;
Intent notificationIntent = new Intent(context, Toggles.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notify.contentIntent = contentIntent;
int HELO_ID = 00000;
NotifyM.notify(HELLO_ID, Notify);
}
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.leozar100.myapp.NotifyService");
context.startService(serviceIntent);
}
public static boolean getBootup(Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(BOOTUP_KEY, BOOTUP_TRUE);
}
}
The service that I start does nothing I just initiate one because I think it just helps the broadcast receiver work. Also this broadcast receiver is registered in my manifest like so:
<receiver android:name=".BootupReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
Which starts on bootup requiring the permission android.permission.RECEIVE_BOOT_COMPLETED
Reference to my question can be found here
P.S. Welcome to stackoverflow
Related
i m creating custoom notification in my app.the notification shows up,but when i click on button,the button doesnt work.i dont know what to do.i looked in all the answer on stackoverflow but didnt get the idea.so,please help me.
this is code for notification
private void customNotification() {
Intent closeButton = new Intent("Download_Cancelled");
closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(getContext(), 0, closeButton, 0);
RemoteViews notificationView = new RemoteViews(getContext().getPackageName(), R.layout.notification);
NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
.setSmallIcon(R.drawable.music)
.setContent(notificationView)
.setChannelId(ID);
notificationView.setOnClickPendingIntent(R.id.next, pendingSwitchIntent);
notificationManager.notify(0, builder.build());
}
this is broadcast activity
public class NotificationBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"thanks",Toast.LENGTH_LONG).show();
}
}
this is manifest
<receiver android:name=".BlankFragment2$NotificationBroadcast">
<intent-filter>
<action android:name="Download_Cancelled" />
</intent-filter>
</receiver>
This is my code. It works fine, if I use this in a separate Android studio project. But when I integrate the code to another project it is causing a problem.
If app is open I am able to receive the notifications. But on app close, the notifications are not received.
Also I have observed one thing - I set my alarm at 1:10 (let's say) and close, and re-open the app at 1.09. I am receiving the notification at 1.10 !!.
I am not able to identify what's happening. Please tell me even if am doing silly mistake, Thank you.
public class BroadCast {
public void broadcastIntent(int selected, Context context, long userMilli) {
Intent intent = new Intent(context.getApplicationContext(), ReminderReceiver.class);
Bundle bundle = new Bundle();
bundle.putInt("selected", selected);
intent.putExtras(bundle);
intent.setAction("android.media.action.DISPLAY_NOTIFICATION");
intent.addCategory("android.intent.category.DEFAULT");
Calendar calendar = Calendar.getInstance();
long curMilli = calendar.getTimeInMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), selected, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (userMilli-curMilli), pendingIntent);
else
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (userMilli-curMilli), pendingIntent);
}
}
Above code creates an intent and broadcast using alarmManager.
public class ReminderReceiver extends BroadcastReceiver {
public ReminderReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
int selected = bundle.getInt("selected");
sendNotification(context, selected);
}
private void sendNotification(Context context, int selected) {
String notificationContentText = "String to display";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.alarm)
.setContentTitle("Title")
.setPriority(Notification.PRIORITY_MAX)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(notificationContentText)
.setColor(Color.rgb(58,95,205));
notificationManager.notify(selected, builder.build());
}
}
Above code building the notification
This is my AndroidManifest file
<receiver
android:name=".ReminderReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
It was not the problem of BroadcastReceiver or the Service. I had to change my notification settings in my mobile. I use Asus, there you have to check power management option. If it is in power saving mode then the notifications are denied on app close.
I'm trying to dismiss a notification from an .addAction() without having to open the app. The problem is when the button is pressed nothing happens, the onReceive() method doesn't trigger.
Here is the code on the MainActivity:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("id", SOMENUMBER);
PendingIntent pIntent = PendingIntent.getBroadcast(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext);
notification.setContentTitle("");
notification.setContentText(t);
notification.setSmallIcon(R.mipmap.ic_launcher);
notification.setOngoing(true);
notification.addAction(R.mipmap.ic_launcher, "Dismiss", pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(SOMENUMBER, notification.build());
And on other class I have the reciever:
public class Notification extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(intent.getIntExtra("id", 0));
}
}
And the reciever on the AndroidManifest.xml file:
<receiver android:name=".MainActivity">
<intent-filter>
<action android:name="io.github.seik.Notification" />
</intent-filter>
</receiver>
Your naming conventions are confusing. Android already has a class called Notification, so you probably shouldn't call your receiver Notification :-(
If MainActivity extends Activity then you need to have a manifest entry for it that looks like this:
<activity android:name=".MainActivity"/>
For your BroadcastReceiver, you need a manifest entry like this:
<receiver android:name=".Notification"
android:exported="true"/>
Since you are using an explicit Intent to launch your BroadcastReceiver, you don't need to provide an <intent-filter> for it. Since the BroadcastReceiver will be started by the NotificationManager, you need to make sure that it is exported.
You then need to create the PendingIntent so that it actually launches your BroadcastReceiver, so change this:
Intent notificationIntent = new Intent(mContext, MainActivity.class);
to this:
Intent notificationIntent = new Intent(mContext, Notification.class);
I want to trigger a Broadcast receiver from the notification. When I click on a button which is on the notification it shows this error:
"Unable to instantiate receiver com.example.testservice.myBroad:
java.lang.ClassCastException: com.example.testservice.myBroad cannot
be cast to android.content.BroadcastReceiver"
**updated/ edited and its working now **
Can you please help to handle 2 buttons from notification to broadcast receiver?
How can I pass extra value from notification broadcast trigger to a receiver that whether its play button pressed or pause?
Now my button working but when I click on notification text it does not take me into my activity. Any help?
I write this code for 2 buttons with extra on intent.
RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent clickIntent = new Intent();
clickIntent.putExtra("button","pause");
clickIntent.setAction(ACTION_DIALOG);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, clickIntent, pendingFlag);
layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent);
builder.setContent(layout);
layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent click = new Intent();
clickIntent.putExtra("Button","play");
clickIntent.setAction(ACTION_DIALOG);
PendingIntent pi1 = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, click, pendingFlag);
layout.setOnClickPendingIntent(R.id.notification_button1,pi1);
builder.setContent(layout);
myBroad receiver file
Bundle extrasBundle = intent.getExtras();
String str = (String) extrasBundle.get("button");
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
context.stopService(new Intent(context, myPlayService.class));
Here is my code:
void showNotification() {
int pendingRequestCode = 0;
int pendingFlag = 0;
final Resources res = getResources();
final NotificationManager notificationManager = (NotificationManager) getSystemService(
NOTIFICATION_SERVICE);
Intent intent = new Intent(MainActivity.this,myBroad.class);
PendingIntent pi= PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_search)
.setAutoCancel(true)
.setTicker("this is notification")
.setContentIntent(getDialogPendingIntent("Tapped the notification entry."));
// Sets a custom content view for the notification, including an image button.
RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
Intent clickIntent = new Intent();
clickIntent.setAction(ACTION_DIALOG);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, clickIntent, pendingFlag);
layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent);
builder.setContent(layout);
// Notifications in Android 3.0 now have a standard mechanism for displaying large
// bitmaps such as contact avatars. Here, we load an example image and resize it to the
// appropriate size for large bitmaps in notifications.
Bitmap largeIconTemp = BitmapFactory.decodeResource(res,
R.drawable.notification_default_largeicon);
Bitmap largeIcon = Bitmap.createScaledBitmap(
largeIconTemp,
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
false);
largeIconTemp.recycle();
builder.setLargeIcon(largeIcon);
notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
}
PendingIntent getDialogPendingIntent(String dialogText) {
return PendingIntent.getActivity(
this,
dialogText.hashCode(), // Otherwise previous PendingIntents with the same
// requestCode may be overwritten.
new Intent(ACTION_DIALOG)
.putExtra(Intent.EXTRA_TEXT, dialogText)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
0);
}
myBroad.class
public class myBroad extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "received", Toast.LENGTH_SHORT).show();
context.stopService(new Intent(context, myPlayService.class));
}
}
Manifest file is:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".myBroad">
<intent-filter >
<action android:name="android.intent.action.MEDIA_BUTTON"/>
</intent-filter>
</receiver>
<service android:name="com.example.testservice.myPlayService" android:icon="#drawable/ic_action_search" android:label="#string/app_name" android:enabled="true"/>
</application>
Because myBroad is an activity object, and not a broadcast object...
Instead of extending (inheritance) from activity, and then making an internal class which extends broadcastreceiver, then just inherit directly from broadcastreceiver.
In your method getDialogPendingIntent you should use PendingIntent.getBroadcast instead of PendingIntent.getActivity. This will cause your PendingIntent to push a broadcast.
And fix this:
public class myBroad extends BroadcastReceiver
Exception says it clearly - your myBroad have to extend BroadcastReceiver, not Activity as it does now.
PS: you should consider switching to proper naming convenction. So it should be MyBroad (class) but myBroad (object of that class). i.e.:
MyBroad myBroad = new MyBroad();
In my app, i am setting the Notification as like below code:
// for the PAYE 18 APRIL 2011 // 1
AM_EM_APRIL_2011 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent in1 = new Intent(this, AlarmReceiverNotificationForEveryMonth.class);
in1.putExtra("MyMessage","Your PAYE return is DUE on 20th April 2011.");
PI_EM_APRIL_2011 = PendingIntent.getBroadcast(this, 1, in1, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar_PAYE_18_APRIL_2011 = Calendar.getInstance();
calendar_PAYE_18_APRIL_2011.setTimeInMillis(System.currentTimeMillis());
calendar_PAYE_18_APRIL_2011.set(2011, 3, 18,mHour, mMinute, 0);
AM_EM_APRIL_2011.set(AlarmManager.RTC_WAKEUP, calendar_PAYE_18_APRIL_2011.getTimeInMillis(),PI_EM_APRIL_2011);
Broadcast class for notification is:
public class AlarmReceiverNotificationForTwoMonth extends BroadcastReceiver{
//private Intent intent;
private NotificationManager notificationManager;
private Notification notification;
public static CharSequence contentText;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// My Notification Code
notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.app_icon;
//System.out.println("The ID Number is: "+Long.parseLong(intent.getData().getSchemeSpecificPart()) );
contentText = intent.getStringExtra("MyMessage");
System.out.println("The Message is: "+intent.getStringExtra("MyMessage"));
CharSequence text = "Your tax amount due period";
CharSequence contentTitle = "Tax Calculator App";
long when = System.currentTimeMillis();
intent = new Intent(context, MenuPageActivity.class);
intent.putExtra("twoMonth", "twoMonth");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new Notification(icon,text,when);
long[] vibrate = {0,100,200,300};
notification.vibrate = vibrate; // To vibrate the Device
notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;
notification.defaults |= Notification.DEFAULT_LIGHTS;
//notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(NotificationConstants.NOTIFICATION_ID_TWO_MONTH, notification);
}
}
All Works good with this code. and i got the Notification. But using this i got notification everytime when ever i restart the device. and there are no any message in that notification. Why it is happend like this???
Please help me for this. or what wrong in my code ???
Thanks.
Edited
I have done like this in manifest.xml
<!-- To receive the Alarm Notification for two months-->
<receiver android:name=".AlarmReceiverNotificationForTwoMonth" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
Is your AlarmReceiverNotificationForTwoMonth class specified in your manifest as the receiver of the BOOT_COMPLETED broadcast?
If so, then the AlarmReceiverNotifictionForTwoMonth.onReceive() method will be triggered every time the device has booted, and as a result show a notification.
EDIT: Your approach with using the AlarmManager is good. The only problem is that alarms are not restored when the device is rebooted. Therefore you need to recreate any existing alarm when the device reboots. My suggestion would be to change your manifest to this:
<receiver android:name=".AlarmReceiverNotificationForTwoMonth" android:enabled="true" >
</receiver>
<receiver android:name=".RecreateAlarms" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Then create a new class
public class RecreateAlarms extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// reschedule alarms here
}
I don't know your logic when an alarm should be triggered. You may need to save an alarm to a file/database in your AlarmReceiverNotificationForTwoMonth method and read it in the RescheduleAlarms to know if there are any alarms to recreate