Urban Airship Android Client-helium Push

Source: Internet
Author: User

This article link: http://blog.csdn.net/kongxx/article/details/8176986


Tell me today how to create an Android application that is the simplest to receive urban airship notifications.

1. To create an Android application first, it is important to note that the package name of the Android application must match the package name of the application on the urban airship.

2. Add Urbanairship-lib-2.0.1.jar to the Libs directory and include it in the classpath of the project.

3. Modify the Androidmanifest.xml file, similar to the following

<manifest xmlns:android= "http://schemas.android.com/apk/res/android" package= "Urbanairship.client" Android:  Versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "15" /> <uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission " Android.permission.ACCESS_NETWORK_STATE "/> <uses-permission android:name=" android.permission.RECEIVE_BOOT_ COMPLETED "/> <uses-permission android:name=" Android.permission.VIBRATE "/> <uses-permission android: Name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name= "
		Android.permission.BROADCAST_STICKY "/> <application android:name=" Urbanairship.client.MyApplication " Android:enabled= "true" 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 Droid:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <receiver Android:name= "Com.urbanairship.CoreReceiver" > <intent-filter> <action android:name= "Android.intent.ac tion.
		Boot_completed "/> <action android:name= android.intent.action.ACTION_SHUTDOWN"/> </intent-filter>  </receiver> <service android:name= "Com.urbanairship.push.PushService" android:label= "Push Notification" Service "android:process=": com.urbanairship.process "/> <service android:name=" Com.urbanairship.push.PushWo Rkerservice "android:label=" Push Notification Worker Service "android:process=": com.urbanairship.process "/> &L T;service android:name= "Com.urbanairship.analytics.EventService" android:label= "Event Service" android:process= ": Com.urbanairship.proCess "/> <service android:name= com.urbanairship.push.PushService"/> <receiver "android:name=" Ip.client.IntentReceiver "/> <provider android:name=" Com.urbanairship.UrbanAirshipProvider "Android:authori" Ties= "Urbanairship.client.urbanairship.provider" android:exported= "false" android:multiprocess= "true"/> </a Pplication> </manifest>
4. Create the Airshipconfig.properties file in the assets directory as follows:
Developmentappkey = Your Development app key
Developmentappsecret = Your Development app key
Productionappkey = Yo ur Production App Key
productionappsecret = Your Production Secret

#transport is "GCM" or "helium".
Transport = Helium

#gcmSender = GCM Sender ID
#Your GCM Sender ID is Your Google API Project ID (required for GCM)

inproduction = False
iapenabled = False

# 2 = log.verbose 3 = log.debug; 4 = log.info;
# 5 = Log.warn; 6 = Log.error; 7 = Log.assert;
Developmentloglevel = 3
productionloglevel = 6
Note Replace the Developmentappkey and Developmentappsecret values (which can be obtained from the application created in the urban airship)

5. Modify the Res/values/strings.xml file, add a few values first, then use the following

<resources>

	<string name= "app_name" >urbanairship-client</string>
	<string name= " Hello_world ">hello world!</string>
	<string name=" menu_settings ">Settings</string>
	<string name= "Title_activity_main" >MainActivity</string>
	<string name= "Enable_push" >enable push</string>
	<string name= "Notification_subject" >Subject</string>
	<string name= " Notification_message ">Message</string>

</resources>
6. Modify the layout file, the project defaults to create a activity_main.xml, here also need to add a layout to display notification. Activity_main.xml (there may be an error here, because some Java files will be added later, if prompted to ignore the error first)

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"
    xmlns:tools= "http:// Schemas.android.com/tools "
    android:layout_width=" match_parent "
    android:layout_height=" Match_parent " >

    <textview
        android:id= "@+id/textview1"
        android:layout_width= "Wrap_content"
        android: layout_height= "Wrap_content"
        android:layout_centerhorizontal= "true"
        android:layout_centervertical= " True "
        android:text=" @string/hello_world "
        tools:context=". Mainactivity "/>

    <checkbox
        android:id=" @+id/enable_push "android:layout_width=" Match_
        Parent "
        android:layout_height=" wrap_content "
        android:layout_alignparenttop=" true "
        Android: Layout_centerhorizontal= "true"
        android:layout_margintop= "31DP"
        android:text= "@string/enable_push" >

</RelativeLayout>
Notification.xml
<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" fill_parent "android:orientation=" vertical "android:layout_alignparenttop=" true "android:layout_height=" fill_parent "> <imageview android:id=" @+id/icon "android:contentdescription = "" "Android:layout_width=" 24dip "android:layout_height=" 24dip "/> <textview android:id=" @+id/su Bject "android:text=" @string/notification_subject "android:layout_aligntop=" @+id/icon "android:layout_to" rightof= "@+id/icon" android:layout_height= "wrap_content" android:layout_width= "Wrap_content" Android:max lines= "1"/> <textview android:id= "@+id/message" android:textsize= "14dip" android:textcolor= "#FF00000
      0 "android:text=" @string/notification_message "android:maxlines=" 1 "android:layout_margintop=" 3dip " Android:layout_height= "WraP_content "android:layout_below=" @+id/subject "android:layout_width=" wrap_content "/> </RelativeLayout& Gt
7. Start working on Java code Now

7.1 First add a checkbox to the Mainactivity.java to explicitly handle the Enable push function, and select the Enable Push function and print out the Apid, where apid can be seen in the log, This apid is required later to send messages from urban airship.

Mainactivity.java

Package urbanairship.client;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.View.OnClickListener;

Import Android.widget.CheckBox;
Import Com.urbanairship.push.PushManager;

Import com.urbanairship.push.PushPreferences;
	
	public class Mainactivity extends activity {private static final String LogTag = MainActivity.class.getName ();
	
	Private CheckBox Enablepush;
		@Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
		
		Setcontentview (R.layout.activity_main);
		Enablepush = (CheckBox) This.findviewbyid (R.id.enable_push);
		Enablepush.setenabled (TRUE);
					Enablepush.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {if (enablepush.ischecked ()) {
					Pushmanager.enablepush ();
					Pushpreferences pref = pushmanager.shared (). Getpreferences ();
				LOG.I (LogTag, "apid:" + Pref.getpushid ());
				} else {	Pushmanager.disablepush ();
	}
			}
		});
		@Override public boolean Oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.activity_main, menu);
	return true; }
}
7.2 Starting now is the receiving notification class

Package urbanairship.client;
Import Android.content.BroadcastReceiver;
Import Android.content.Context;
Import android.content.Intent;

Import Android.util.Log;
Import com.urbanairship.UAirship;

Import Com.urbanairship.push.PushManager;

Import Java.util.Set; public class Intentreceiver extends Broadcastreceiver {private static final String LogTag = IntentReceiver.class.getNam

	E (); @Override public void OnReceive (context context, Intent Intent) {log.i (LogTag, "Received Intent:" + intent.tostring ()
		);

		String action = Intent.getaction (); if (Action.equals (pushmanager.action_push_received)) {int id = Intent.getintextra (pushmanager.extra_notification_id
			
			, 0); LOG.I (LogTag, "Received push notification.
			Alert: "+ Intent.getstringextra (Pushmanager.extra_alert) +" [notificationid= "+ ID +"]);
		Logpushextras (Intent); else if (action.equals (pushmanager.action_notification_opened)) {log.i (LogTag, "User clicked NOTIFICATION.") Message: "+ Intent.getstringextra (Pushmanager.extra_alert));

			Logpushextras (Intent);
			Intent launch = new Intent (intent.action_main);
			Launch.setclass (Uairship.shared (). Getapplicationcontext (), mainactivity.class);

			Launch.setflags (Intent.flag_activity_new_task);
		Uairship.shared (). Getapplicationcontext (). StartActivity (Launch); else if (action.equals (pushmanager.action_registration_finished)) {LOG.I (LogTag, registration complete.) Apid: "+ Intent.getstringextra (pushmanager.extra_apid) +".
		Valid: "+ Intent.getbooleanextra (Pushmanager.extra_registration_valid, false)); else if (action.equals (pushmanager.action_gcm_deleted_messages)) {log.i (LogTag, "The GCM service DELETED" + intent.)
		Getstringextra (pushmanager.extra_gcm_total_deleted) + "messages.");
		}} private void Logpushextras (Intent Intent) {set<string> keys = Intent.getextras (). Keyset (); 
		for (String Key:keys) {log.i (LogTag, "Push Notification Extra: [" + Key + ":" + Intent.getstringextra (Key) + "]"); }
	}
} 
7.3 Finally, a application class that is used to process and display notification.
Package urbanairship.client;
Import android.app.Application;

Import Android.util.Log;
Import com.urbanairship.AirshipConfigOptions;
Import Com.urbanairship.Logger;
Import com.urbanairship.UAirship;
Import Com.urbanairship.push.CustomPushNotificationBuilder;

Import Com.urbanairship.push.PushManager;
		public class MyApplication extends application {@Override public void onCreate () {super.oncreate ();

		Airshipconfigoptions options = Airshipconfigoptions.loaddefaultoptions (this);
		Uairship.takeoff (this, options);

		Logger.loglevel = Log.verbose;
		Custompushnotificationbuilder CPNB = new Custompushnotificationbuilder ();
		Cpnb.statusbaricondrawableid = R.drawable.ic_launcher;
		Cpnb.layout = r.layout.notification;
		Cpnb.layouticondrawableid = r.drawable.ic_launcher;//Custom layout icon Cpnb.layouticonid = R.id.icon;
		Cpnb.layoutsubjectid = R.id.subject;

		Cpnb.layoutmessageid = R.id.message;
		Pushmanager.shared (). Setnotificationbuilder (CPNB); Pushmanager.shared (). SetinTentreceiver (Intentreceiver.class); }
}
8. Test

8.1 First run the Android application created above and get apid from Japan.

8.2 Then send notification to this apid from the urban airship.

8.3 Wait a moment, will receive the notification on the status bar of the Andorid simulator.










Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.