Posted on by Tobias Knell | Posted in Mobile Blog | Tagged , , ,

If you need to send apple push notifications to your users, like we do in a secret project mentioned earlier this week, notnoop's java-apns library is a good choice, because its really simple to use and saves you a lot of work.

(I presume that you already know how to get the Tokens of your users and already have a certificate for the push notifications, I only show you how easy the server part can be with this library. If you don't know, read this first: Apple Push Service)

First you have to download the library (or add it in your maven dependencies):
java-apns

The programming part isn't that much so here's how you do it:

public void pushMessage() {
		ApnsService service = null;
		try {
			// get the certificate
			InputStream certStream = this.getClass().getClassLoader().getResourceAsStream("your_certificate.p12");
			service = APNS.newService().withCert(certStream, "your_cert_password").withSandboxDestination().build();
			// or
			// service = APNS.newService().withCert(certStream,
			// "your_cert_password").withProductionDestination().build();
			service.start();
			// You have to delete the devices from you list that no longer
			//have the app installed, see method below
			deleteInactiveDevices(service);
			// read your user list
			List<User> userList = userDao.readUsers();
			for (User user : userList) {
				try {
					// we had a daily update here, so we need to know how many
					//days the user hasn't started the app
					// so that we get the number of updates to display it as the badge.
					int days = (int) ((System.currentTimeMillis() - user.getLastUpdate()) / 1000 / 60 / 60 / 24);
					PayloadBuilder payloadBuilder = APNS.newPayload();
					payloadBuilder = payloadBuilder.badge(days).alertBody("some message you want to send here");
					// check if the message is too long (it won't be sent if it is)
					//and trim it if it is.
					if (payloadBuilder.isTooLong()) {
						payloadBuilder = payloadBuilder.shrinkBody();
					}
					String payload = payloadBuilder.build();
					String token = user.getToken();
					service.push(token, payload);
				} catch (Exception ex) {
					// some logging stuff
				}
			}
		} catch (Exception ex) {
			// more logging
		} finally {
			// check if the service was successfull initialized and stop it here, if it was
			if (service != null) {
				service.stop();
			}

		}
	}

	private void deleteInactiveDevices(ApnsService service) {
		// get the list of the devices that no longer have your app installed from apple
		//ignore the ="" after Date here, it's a bug...
		Map<String, Date> inactiveDevices = service.getInactiveDevices();
		for (String deviceToken : inactiveDevices.keySet()) {
			userDao.deleteByDeviceId(deviceToken);
		}

	}

Now wasn't that an easy one this time?



One Response to Sending Apple Push Notifications with notnoop’s java-apns library

  1. Pingback: APN Device Tokens | Mobile Solutions Blog

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>