Android: How to fix BroadcastReceiver in JobIntentService? - notifications

I have an Activity with an AlarmManager that fires a BroadcastReceiver. The BroadcastReceiver fires a JobIntentService to send a Notification to the user.
When the user taps "CLEAR ALL" or swipes to dismiss the Notification, I want the setDeleteIntent() to reset a counter variable "totalMessages" to zero that I set up in a SharedPreferences file. It is not resetting to zero. What am I missing here?
public class AlarmService extends JobIntentService {
static final int JOB_ID = 9999;
public static final String NOTIFICATIONS_COUNTER = "NotificationsCounter";
private static final int REQUEST_CODE_DELETE_INTENT = 1;
int totalMessages = 0;
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, AlarmService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("notification_cleared");
registerReceiver(receiver, filter);
sendNotification();
}
private void sendNotification() {
int notifyID = 1;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
SharedPreferences sp = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
totalMessages = sp.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
SharedPreferences.Editor editor = sp.edit();
editor.putInt("total-messages", ++totalMessages);
editor.apply();
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_announcement_white_24dp)
.setContentText("")
Intent i = new Intent(this, AlarmService.class);
i.setAction("notification_cleared");
PendingIntent deleteIntent = PendingIntent.getBroadcast(this,REQUEST_CODE_DELETE_INTENT,i,PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setDeleteIntent(deleteIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mBuilder.setSubText(String.valueOf(totalMessages));
}
else {
mBuilder.setNumber(totalMessages);
}
if (notificationManager != null) {
notificationManager.notify(notifyID, mBuilder.build());
}
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
if (action.equals("notification_cleared")) {
// Reset the Notifications counter ("total-messages") to zero since the user
// clicked on "CLEAR ALL" Notification or swiped to delete a Notification.
SharedPreferences sp1 = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp1.edit();
editor.clear();
editor.apply();
totalMessages = sp1.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
editor.putInt("total-messages", totalMessages);
editor.apply();
}
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}

The problem is that your broadcast receiver's implementation to clear notifications is within the life-cycle of job. JobIntentService is tasked to show notification and go away thus the broadcast receiver. But when the user clicks on the CLEAR from notification, the pending intent is broadcasted but then there's no one to listen to it.
For a solution, I would suggest you to create a separate broadcast receiver and register it in your AndroidManifest.xml. By then your broadcast will always be listened and you can perform what ever within..

Related

Push notification after successful payment for mobile apps

I need help how to send push notifications on successful payment with transaction I'd to user
Use one of the background workers if you want to check the status of your transaction in background. I will use WorkManager.
implementation "android.arch.work:work-runtime:1.0.1"
public class SynchronizeWorker extends Worker {
static final String TAG = "MYWORKER";
public SynchronizeWorker(#NonNull Context context, #NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
private Notification getNotification() {
NotificationManager mNotificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"WTF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("WTF_CHANNEL_DESCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
// specify the class of the activity you want to open after click on notification
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(),
0,
intent,
0);
return new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getApplicationContext().getResources().getString(R.string.notification_header))
.setContentText(getApplicationContext().getResources().getString(R.string.notification_text))
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent)
.build();
}
#NonNull
#Override
public Result doWork() {
Log.d(TAG, "status checking started");
// check your transaction status here and show notification
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Log.d(TAG, "status checking finished");
}
Log.d(TAG, "status checking finished");
NotificationManagerCompat
.from(getApplicationContext())
.notify((int)(Math.random() * 10), getNotification());
return Result.success();
}
}
And then enqueue worker where you want to check status
OneTimeWorkRequest myWorkRequest = new OneTimeWorkRequest.Builder(SynchronizeWorker.class).build();
WorkManager.getInstance().enqueue(myWorkRequest);
I understand that it is probably not exactly what you want, but hope it will help somehow:)

Notification "setSound()" in Android 8

Here's the question, the code of notification can't work with Android 8.
I can't set the notification sound myself. The only result it shows is the system sound "Bee".
Here's my code:
if(Build.VERSION.SDK_INT>=26) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "channel_1";
String description = "123";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, "123", importance);
mChannel.enableLights(true);
mChannel.enableVibration(true);
mChannel.setLightColor(Color.GREEN);
mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes aa = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
mChannel.setSound(Uri.parse("android.resource://com.example.lenovo.projectmonitor/" + R.raw.video11),aa);
manager.createNotificationChannel(mChannel);
Notification notification = new NotificationCompat.Builder(NotificationService.this, "channel_1")
.setContentTitle("new alarm")
.setContentText(nameAll.get(0))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
manager.notify(1, notification);
}
use setSound method in both NotificationChannel and NotificationCompat.Builder class. example
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getString(R.string.channel_name);
String description = context.getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
channel.setDescription(description);
channel.setSound(null, null);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
and creating buileder:
public void buildNotification(Class className, int smallIconId) {
createNotificationChannel();
// Create an Intent for the activity you want to start
Intent intent = new Intent(context, className);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// Create the TaskStackBuilder and add the intent, which inflates the back stack
// TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// stackBuilder.addNextIntentWithParentStack(intent);
//// Get the PendingIntent containing the entire back stack
// PendingIntent pendingIntent =
// stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder
.setSmallIcon(smallIconId)
.setContentTitle("Recording Audio..")
// .setContentText("Much longer text that cannot fit one line...")
// .setStyle(new NotificationCompat.BigTextStyle()
// .bigText("Much longer text that cannot fit one line..."))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(null)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
// notificationId is a unique int for each notification that you must define
// notificationManager.notify(notificationId, mBuilder.build());
// mBuilder.setContentTitle("changed it");
// notificationManager.notify(notificationId, mBuilder.build());
// mHandler.postDelayed(new Runnable() {
// #Override
// public void run() {
// }
// }, 3000);
}

NativeExpressAdView java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

I am working on android app which fetch data using RecyclerView and Retrofit for parsing JSON Url. I had following tutorial on this Github
My project on Android Studio has no Errors and I'm able to run the Application. But when I open the MainActivity it crashes.
Error that i am get
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
This is the following line is on setUpAndLoadNativeExpressAds
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
This is MainActivity
public class MainActivity extends AppCompatActivity{
public static final int ITEMS_PER_AD = 3;
private static final int NATIVE_EXPRESS_AD_HEIGHT = 150;
private static final String AD_UNIT_ID = ADMOB_NATIVE_MENU_ID;
private StartAppAd startAppAd = new StartAppAd(this);
private RecyclerView mRecyclerView;
private List<Object> mRecyclerViewItems = new ArrayList<>();
private KontenAdapter kontenAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// Use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView.
mRecyclerView.setHasFixedSize(true);
// Specify a linear layout manager.
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
// mRecyclerViewItems = new ArrayList<>();
// Update the RecyclerView item's list with menu items and Native Express ads.
// addMenuItemsFromJson();
loadJSON();
// initData();
setUpAndLoadNativeExpressAds();
}
/**
* Adds Native Express ads to the items list.
*/
private void addNativeExpressAds() {
// Loop through the items array and place a new Native Express ad in every ith position in
// the items List.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = new NativeExpressAdView(MainActivity.this);
mRecyclerViewItems.add(i, adView);
}
}
/**
* Sets up and loads the Native Express ads.
*/
private void setUpAndLoadNativeExpressAds() {
mRecyclerView.post(new Runnable() {
#Override
public void run() {
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
// Set the ad size and ad unit ID for each Native Express ad in the items list.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
final CardView cardView = (CardView) findViewById(R.id.ad_card_view);
final int adWidth = cardView.getWidth() - cardView.getPaddingLeft()
- cardView.getPaddingRight();
AdSize adSize = new AdSize((int) (adWidth / scale), NATIVE_EXPRESS_AD_HEIGHT);
adView.setAdSize(adSize);
adView.setAdUnitId(AD_UNIT_ID);
}
// Load the first Native Express ad in the items list.
loadNativeExpressAd(0);
}
});
}
/**
* Loads the Native Express ads in the items list.
*/
private void loadNativeExpressAd(final int index) {
if (index >= mRecyclerViewItems.size()) {
return;
}
Object item = mRecyclerViewItems.get(index);
if (!(item instanceof NativeExpressAdView)) {
throw new ClassCastException("Expected item at index " + index + " to be a Native"
+ " Express ad.");
}
final NativeExpressAdView adView = (NativeExpressAdView) item;
// Set an AdListener on the NativeExpressAdView to wait for the previous Native Express ad
// to finish loading before loading the next ad in the items list.
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// The previous Native Express ad loaded successfully, call this method again to
// load the next ad in the items list.
loadNativeExpressAd(index + ITEMS_PER_AD);
}
#Override
public void onAdFailedToLoad(int errorCode) {
// The previous Native Express ad failed to load. Call this method again to load
// the next ad in the items list.
Log.e("MainActivity", "The previous Native Express ad failed to load. Attempting to"
+ " load the next Native Express ad in the items list.");
loadNativeExpressAd(index + ITEMS_PER_AD);
}
});
// Load the Native Express ad.
adView.loadAd(new AdRequest.Builder().build());
}
private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.myjson.com/") //https://api.myjson.com/bins/v4dzd
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
/**
* Adds {#link KontenItem}'s from a JSON file.
*/
private void addMenuItemsFromJson() {
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
String menuItemName = menuItemObject.getString("name");
String menuItemDescription = menuItemObject.getString("description");
String menuItemPrice = menuItemObject.getString("price");
String menuItemCategory = menuItemObject.getString("category");
String menuItemImageName = menuItemObject.getString("photo");
String menuItemUrl = menuItemObject.getString("url");
KontenItem kontenItem = new KontenItem(menuItemName, menuItemDescription, menuItemPrice,
menuItemCategory, menuItemImageName, menuItemUrl);
mRecyclerViewItems.add(kontenItem);
}
} catch (IOException | JSONException exception) {
Log.e(MainActivity.class.getName(), "Unable to parse JSON file.", exception);
}
}
/**
* Reads the JSON file and converts the JSON data to a {#link String}.
*
* #return A {#link String} representation of the JSON data.
* #throws IOException if unable to read the JSON file.
*/
private String readJsonDataFromFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputStream = getResources().openRawResource(R.raw.menu_items_json);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is MyAdapter
public class KontenAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
// A menu item view type.
private static final int MENU_ITEM_VIEW_TYPE = 0;
// The Native Express ad view type.
private static final int NATIVE_EXPRESS_AD_VIEW_TYPE = 1;
// An Activity's Context.
private final Context mContext;
// The list of Native Express ads and menu items.
private final List<Object> mRecyclerViewItems;
public KontenAdapter(List<Object> recyclerViewItems, Context context) {
this.mContext = context;
this.mRecyclerViewItems = recyclerViewItems;
}
/**
* The {#link MenuItemViewHolder} class.
* Provides a reference to each view in the menu item view.
*/
public class MenuItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView menuItemName;
private TextView menuItemDescription;
private TextView menuItemPrice;
private TextView menuItemCategory;
private ImageView menuItemImage;
private TextView menuItemUrl;
MenuItemViewHolder(View view) {
super(view);
menuItemImage = (ImageView) view.findViewById(R.id.menu_item_image);
menuItemName = (TextView) view.findViewById(R.id.menu_item_name);
menuItemPrice = (TextView) view.findViewById(R.id.menu_item_price);
menuItemCategory = (TextView) view.findViewById(R.id.menu_item_category);
menuItemDescription = (TextView) view.findViewById(R.id.menu_item_description);
menuItemUrl = (TextView) view.findViewById(R.id.menu_item_url);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent detailIntent = new Intent(v.getContext(), PostActivity.class);
detailIntent.putExtra("name",menuItemName.getText().toString() );
detailIntent.putExtra("url", menuItemUrl.getText().toString());
mContext.startActivity(detailIntent);
}
}
/**
* The {#link NativeExpressAdViewHolder} class.
*/
public class NativeExpressAdViewHolder extends RecyclerView.ViewHolder {
NativeExpressAdViewHolder(View view) {
super(view);
}
}
#Override
public int getItemCount() {
return mRecyclerViewItems.size();
}
/**
* Determines the view type for the given position.
*/
#Override
public int getItemViewType(int position) {
return (position % MainActivity.ITEMS_PER_AD == 0) ? NATIVE_EXPRESS_AD_VIEW_TYPE
: MENU_ITEM_VIEW_TYPE;
}
/**
* Creates a new view for a menu item view or a Native Express ad view
* based on the viewType. This method is invoked by the layout manager.
*/
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
View menuItemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.menu_item_container, viewGroup, false);
return new MenuItemViewHolder(menuItemLayoutView);
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
View nativeExpressLayoutView = LayoutInflater.from(
viewGroup.getContext()).inflate(R.layout.native_express_ad_container,
viewGroup, false);
return new NativeExpressAdViewHolder(nativeExpressLayoutView);
}
}
/**
* Replaces the content in the views that make up the menu item view and the
* Native Express ad view. This method is invoked by the layout manager.
*/
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int viewType = getItemViewType(position);
switch (viewType) {
case MENU_ITEM_VIEW_TYPE:
MenuItemViewHolder menuItemHolder = (MenuItemViewHolder) holder;
KontenItem kontenItem = (KontenItem) mRecyclerViewItems.get(position);
// Get the menu item image resource ID.
String imageName = kontenItem.getImageName();
int imageResID = mContext.getResources().getIdentifier(imageName, "drawable",
mContext.getPackageName());
// Add the menu item details to the menu item view.
menuItemHolder.menuItemImage.setImageResource(imageResID);
menuItemHolder.menuItemName.setText(kontenItem.getName());
menuItemHolder.menuItemPrice.setText(kontenItem.getPrice());
menuItemHolder.menuItemCategory.setText(kontenItem.getCategory());
menuItemHolder.menuItemDescription.setText(kontenItem.getDescription());
menuItemHolder.menuItemUrl.setText(kontenItem.getInstructionUrl());
break;
case NATIVE_EXPRESS_AD_VIEW_TYPE:
// fall through
default:
NativeExpressAdViewHolder nativeExpressHolder =
(NativeExpressAdViewHolder) holder;
NativeExpressAdView adView =
(NativeExpressAdView) mRecyclerViewItems.get(position);
ViewGroup adCardView = (ViewGroup) nativeExpressHolder.itemView;
// The NativeExpressAdViewHolder recycled by the RecyclerView may be a different
// instance than the one used previously for this position. Clear the
// NativeExpressAdViewHolder of any subviews in case it has a different
// AdView associated with it, and make sure the AdView for this position doesn't
// already have a parent of a different recycled NativeExpressAdViewHolder.
if (adCardView.getChildCount() > 0) {
adCardView.removeAllViews();
}
if (adView.getParent() != null) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Add the Native Express ad to the native express ad view.
adCardView.addView(adView);
}
}
}
KontenItem.java
class KontenItem {
private final String name;
private final String description;
private final String price;
private final String category;
private final String imageName;
private final String instructionUrl;
public KontenItem(String name, String description, String price, String category,
String imageName, String instructionUrl) {
this.name = name;
this.description = description;
this.price = price;
this.category = category;
this.imageName = imageName;
this.instructionUrl = instructionUrl;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getPrice() {
return price;
}
public String getCategory() {
return category;
}
public String getImageName() {
return imageName;
}
public String getInstructionUrl() {
return instructionUrl;
}
}
Thanks in advance!
You are calling addNativeExpressAds() and
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
in different threads. So, mRecyclerViewItems.get(i) is used before its initialization.
I would suggest to use
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
mRecyclerViewItems = new ArrayList<Object>(Arrays.asList(jsonResponse.getKonten()));
addNativeExpressAds();
RecyclerView.Adapter adapter = new KontenAdapter(mRecyclerViewItems, getApplicationContext());
mRecyclerView.setAdapter(adapter);
setUpAndLoadNativeExpressAds(); // << ADD THIS METHOD HERE AND REMOVE THE OTHER CALLING
}
Your problem is that mRecyclerViewItems is a zero based array/collection. Yet in setUpAndLoadNativeExpressAds() you will iterate even if you have no elements, and then ask for element 0.
for (int i = 0; i <= mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
final NativeExpressAdView adView = (NativeExpressAdView) mRecyclerViewItems.get(i);
..
}
you should instead
for (int i = 0; i < mRecyclerViewItems.size(); i += ITEMS_PER_AD) {
..
}

Parse | Push Notification Straight Into Web View, How?

I've searched in the web, parse docs and ask many people but no one can point me how to do it.
I have an RSS app who getting the articles into a UITableView.
when I'm sending a Push it's open the app itself but not the article I want to (well obviously since I don't know how to code that) .
Can anyone please give me ideas how to do it ?
(code sample will be useful as well) .
First of all you have to implement your own Receiver class instead of default Parse push receiver and put it into AndroidManifest.xml as follows :
<receiver android:name="net.blabla.notification.PushNotifHandler" android:exported="false">
<intent-filter>
<action android:name="net.bla.PUSH_MESSAGE" />
</intent-filter>
</receiver>
In your PushNotifHandler.java class you should put some parameters to Intent you will throw as follows :
public class PushNotifHandler extends BroadcastReceiver{
private static final String TAG = PushNotifHandler.class.getSimpleName();
private static int nextNotifID = (int)(System.currentTimeMillis()/1000);
private static final long VIBRATION_DURATION = 500;
#Override
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
Intent resultIntent = new Intent(context, ToBeOpenedActivity.class);
JSONObject jsonData = new JSONObject(intent.getExtras().getString("com.parse.Data"));
fillNotificationData(jsonData, action, resultIntent);
String title = jsonData.getString("messageTitle") + "";
String message = jsonData.getString("messageText") + "";
TaskStackBuilder stackBuilder = TaskStackBuilder.from(context);
stackBuilder.addParentStack(ToBeOpenedActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
Notification notification;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).
setSmallIcon(R.drawable.icon).
setContentTitle(title).
setContentText(message).
setAutoCancel(true);
builder.setContentIntent(resultPendingIntent);
notification = builder.getNotification();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(TAG, nextNotifID++, notification);
vibratePhone(context);
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
private void vibratePhone(Context context) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATION_DURATION);
}
private void fillNotificationData(JSONObject json, String action, Intent resultIntent)
throws JSONException {
Log.d(TAG, "ACTION : " + action);
resultIntent.putExtra("paramString", json.getString("paramFromServer"));
}
}
With key "com.parse.Data" you will get parameters sent from your server code as json format.After getting paramString and paramBoolean parameters from this json, you will put these parameters into new Intent you hav created as seen in fillNotificationData method.
Other parts of onReceive method creates a local notification and vibrates the device.
Finally on your activity class onResume() method you will check intent parameters to realize if you are opening the app from push notification or not.
#Override
public void onResume() {
super.onResume();
checkPushNotificationCase(getIntent());
}
private void checkPushNotificationCase(Intent intent) {
Bundle extraParameters = intent.getExtras();
Log.d("checking push notifications intent extras : " + extraParameters);
if (extraParameters != null) {
if(extraParameters.containsKey("paramString")) {
// doSomething
}
}
}
I hope you have asked this question for Android :))

ProximityAlert with a BroadcastReceiver not working

I am new to Android and have a problem with adding ProximityAlert with a BroadcastReceiver. I know that this topic has been taken up earlier as well but I am trying to add proximity alert to different locations and I am not sure if what I am trying to do is quite achievable this way or I am just doing it wrong.
Problem : I have tried to implement the code for adding ProximityAlert with a BroadcastReceiver, but its not working some how. Below is the snippet from my code (posted below) requesting all to please have a look and help me out with it.
I have this userLocations list. I am adding Proximity Alert to all the user mentioned location by running a for loop for the list. I only want to add a proximity Alert to the user location if that particular location has not been visited by the user before.
I then register the receiver in the addLocationProximity() method, which is called from the onResume() method. I unregisterReceiver the receiver in the onPause() method.
I have also used the onLocationChanged() method to populate a list (which I would be needing for later) based on the same logic which have been used to add the proximity alert.
Please do let me know if any of these steps have not been carried out correctly.
Thanks in advance.
package com.android.locationmang;
public class ViewAActivity extends ListActivity implements LocationListener{
private static final String PROX_ALERT_INTENT = "com.android.locationmang.PROX_ALERT_INTENT";
private static final long LOCAL_FILTER_DISTANCE = 1200;
public static List<UserLocation> notifiedLocationsList;
public static Location latestLocation;
PendingIntent pendingIntent;
Intent notificationIntent;
private LocationManager locationManager;
List<UserLocations> userLocations;
private IntentFilter filter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notifiedLocationsList = new ArrayList<UserLocation>();
userLocations = getUserLocations(); //Returns a list of user Locations stored by the user on the DB
filter = new IntentFilter(PROX_ALERT_INTENT);
}
private void setUpLocation() {
locationNotificationReceiver = new LocationNotificationReceiver();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);
for (int i = 0; i < userLocation.size(); i++){
UserLocation userLocation = userLocation.get(i);
if(!(userLocation.isComplete())){
setProximityAlert(userLocation.getLatitude(),
userLocation.getLongitude(),
i+1,
i);
}
}
registerReceiver(locationNotificationReceiver, filter);
}
private void setProximityAlert(double lat, double lon, final long eventID, int requestCode){
// Expiration is 10 Minutes (10mins * 60secs * 1000milliSecs)
long expiration = 600000;
Intent intent = new Intent(this, LocationNotificationReceiver.class);
intent.putExtra(LocationNotificationReceiver.EVENT_ID_INTENT_EXTRA, eventID);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);
locationManager.addProximityAlert(lat, lon, LOCAL_FILTER_DISTANCE, expiration, pendingIntent);
}
#Override
protected void onResume() {
super.onResume();
setUpLocation();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60, 5, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
unregisterReceiver(locationNotificationReceiver);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public boolean userLocationIsWithinGeofence(UserLocation userLocation, Location latestLocation, long localFilterDistance) {
float[] distanceArray = new float[1];
Location.distanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), latestLocation.getLatitude(), latestLocation.getLongitude(), userLocation.getAssignedDate(),distanceArray);
return (distanceArray[0]<localFilterDistance);
}
public void onLocationChanged(Location location) {
if (location != null) {
latestLocation = location;
for (UserLocation userLocation : userLocations) {
if (!(userLocations.isVisited()) && userLocationIsWithinGeofence(userLocation, latestLocation, LOCAL_FILTER_DISTANCE)) {
notifiedLocationsList.add(userLocation);
}
}
}
}
}
Code for BroadcastReceiver
package com.android.locationmang;
public class LocationNotificationReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
public static final String EVENT_ID_INTENT_EXTRA = "EventIDIntentExtraKey";
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
long eventID = intent.getLongExtra(EVENT_ID_INTENT_EXTRA, -1);
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}
else{
Log.d(getClass().getSimpleName(), "exiting");
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
Intent notificationIntent = new Intent(context, MarkAsCompleteActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(context, "Proximity Alert!", "You are near your point of interest.", pendingIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 1500;
notification.ledOffMS = 1500;
return notification;
}
}
Thanks and Regards
You are creating a broadcast Intent with an action string, and your <receiver> element does not have the corresponding <intent-filter>. Change:
Intent intent = new Intent(PROX_ALERT_INTENT);
to:
Intent intent = new Intent(this, LocationNotificationReceiver.class);