java - Updating the UI upon receiving an android push notification -
i have query regarding android push notification , had asked in stackoverflow post , did not out of [query regarding android push notifications. posting again, , follows:
i have android app receives push notifications google push notification service. when tap on received notification, opens ui displays message, list view. now, when user receives push notification, , assuming screen open, ui should refreshed automatically, such displays latest notification. let me know how can solve this?
below code have implemented:
java code receive notification:
import java.util.timer; import java.util.timertask; import android.app.notification; import android.app.notificationmanager; import android.app.pendingintent; import android.content.context; import android.content.intent; import android.os.powermanager; import android.util.log; import com.example.foodu.r; import com.google.android.gcm.gcmbaseintentservice; public class gcmintentservice extends gcmbaseintentservice { private static final string tag = "gcm ::service"; // use project id google api sender_id public static final string sender_id = "53340195486"; public gcmintentservice() { super(sender_id); } @override protected void onerror(context arg0, string errorid) { log.e(tag, "onerror: errorid=" + errorid); } @override protected void onmessage(context context, intent data) { string message; // message php server message = data.getstringextra("message"); // open new activity called gcmmessageview intent intent = new intent(this, com.example.foodu.notification.class); // pass data new activity intent.putextra("message", message); intent.setflags(intent.flag_activity_clear_top); // starts activity on notification click pendingintent pintent = pendingintent.getactivity(this, 0, intent, pendingintent.flag_update_current); // create notification notification builder notification notification = new notification.builder(this) .setsmallicon(r.drawable.ic_logo) .setwhen(system.currenttimemillis()) .setcontenttitle("deals") .setcontenttext(message).setcontentintent(pintent) .getnotification(); // remove notification on click notification.flags |= notification.flag_auto_cancel; notificationmanager manager = (notificationmanager) getsystemservice(notification_service); manager.notify(r.string.app_name, notification); { // wake android device when notification received powermanager pm = (powermanager) context .getsystemservice(context.power_service); final powermanager.wakelock mwakelock = pm.newwakelock( powermanager.full_wake_lock | powermanager.acquire_causes_wakeup, "gcm_push"); mwakelock.acquire(); // timer before putting android device sleep mode. timer timer = new timer(); timertask task = new timertask() { public void run() { mwakelock.release(); } }; timer.schedule(task, 5000); } } @override protected void onregistered(context arg0, string registrationid) { log.i(tag, "onregistered: registrationid=" + registrationid); } @override protected void onunregistered(context arg0, string registrationid) { log.i(tag, "onunregistered: registrationid=" + registrationid); } }
the code corresponding activity launched when user taps on notification:
import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.objectinputstream; import java.io.objectoutputstream; import java.text.simpledateformat; import java.util.linkedlist; import java.util.locale; import java.util.stringtokenizer; import java.util.timezone; import com.example.foodu.r; import com.example.foodu.r.drawable; import com.example.foodu.r.id; import com.example.foodu.r.layout; import com.example.foodu.r.menu; import com.google.android.gcm.gcmregistrar; import android.support.v7.app.actionbaractivity; import android.app.alertdialog; import android.content.clipdata; import android.content.clipboardmanager; import android.content.contentresolver; import android.content.contentvalues; import android.content.context; import android.content.dialoginterface; import android.content.intent; import android.net.uri; import android.os.bundle; import android.provider.calendarcontract; import android.util.log; import android.view.actionmode; import android.view.actionmode.callback; import android.view.menu; import android.view.menuinflater; import android.view.menuitem; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemlongclicklistener; import android.widget.listview; import android.widget.textview; import android.widget.toast; public class notification extends actionbaractivity { linkedlist<notificationdata> notificationlist = new linkedlist<notificationdata>(); listview listview = null; notificationlistadapter adaptor; actionmode mactionmode; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_notification); overridependingtransition(r.anim.trans_left_in, r.anim.trans_left_out); listview = (listview) findviewbyid(r.id.listview1); // retrive data gcmintentservice.java intent = getintent(); string message = i.getstringextra("message"); //getdatafordisplay(); if(message!=null) { parsedata(message); }else{ getdatatodisplay(); } adaptor = new notificationlistadapter(getapplicationcontext(), notificationlist); listview.setadapter(adaptor); textview emptytext = (textview) findviewbyid(r.id.empty); emptytext.settext("no events yet!"); listview.setemptyview(emptytext); listview.setonitemlongclicklistener(new onitemlongclicklistener() { public boolean onitemlongclick(adapterview<?> parent, view view, int position, long id) { onlistitemselect(position); view.setselected(true); return true; } }); } @override protected void onstart() { // todo auto-generated method stub super.onstart(); adaptor.notifydatasetchanged(); } @override protected void onrestart() { // todo auto-generated method stub super.onrestart(); } void writetofile(){ fileoutputstream fos; try { fos = openfileoutput("varun", context.mode_private); objectoutputstream oos = new objectoutputstream(fos); oos.writeobject(notificationlist); oos.close(); }catch (exception e) { // todo auto-generated catch block e.printstacktrace(); } } void readfromfile(){ try{ fileinputstream fis = openfileinput("varun"); objectinputstream ois = new objectinputstream(fis); linkedlist<notificationdata> local = (linkedlist<notificationdata>) ois.readobject(); ois.close(); (int = 0; < local.size(); i++) { notificationlist.add(local.get(i)); } }catch(exception e){ e.printstacktrace(); } } private void getdatatodisplay() { // todo auto-generated method stub readfromfile(); } private void parsedata(string message) { try { int len = 0; string[] stringarr = new string[100]; stringtokenizer st = new stringtokenizer(message, "."); len = st.counttokens(); (int = 0; < len; i++) { if (st.hasmoretokens()) { stringarr[i] = st.nexttoken(); } } notificationdata data = new notificationdata(); data.title = stringarr[0]; data.venue = stringarr[1]; data.date = stringarr[2]; data.time = stringarr[3]; notificationlist.add(data); readfromfile(); } catch (exception e) { e.printstacktrace(); } } private void getdatetodisplay() { // todo auto-generated method stub } @override protected void onpause() { // todo auto-generated method stub super.onpause(); writetofile(); } @override public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.notificationmenu, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { int id = item.getitemid(); if (id == r.id.action_settings) { return true; } if(id == r.id.action_register){ registerdevice(); return true; } return super.onoptionsitemselected(item); } private void registerdevice() { try { gcmregistrar.checkdevice(this); gcmregistrar.checkmanifest(this); gcmregistrar .register(notification.this, gcmintentservice.sender_id); } catch (exception e) { e.printstacktrace(); } } private actionmode.callback mactionmodecallback = new actionmode.callback() { @override public boolean oncreateactionmode(actionmode mode, menu menu) { menuinflater inflater = mode.getmenuinflater(); inflater.inflate(r.menu.notificationcontext, menu); return true; } @override public boolean onprepareactionmode(actionmode mode, menu menu) { return false; } @override public boolean onactionitemclicked(actionmode mode, menuitem item) { switch (item.getitemid()) { case r.id.menu_calender: addtocalender(); mode.finish(); return true; case r.id.menu_delete: //deletedata(); showalertbox(); return false; case r.id.menu_share: sharedate(); mode.finish(); return true; case r.id.menu_copy: copytoclip(); mode.finish(); return true; default: return false; } } @override public void ondestroyactionmode(actionmode mode) { mactionmode = null; adaptor.removeselection(); } }; void onlistitemselect(int position) { adaptor.toggleselection(position); boolean hascheckeditems = adaptor.getselectedcount() > 0; if (hascheckeditems && mactionmode == null) { mactionmode = startactionmode((callback) mactionmodecallback); } else if (!hascheckeditems && mactionmode != null) { mactionmode.finish(); } if (mactionmode != null) mactionmode.settitle(string.valueof(adaptor.getselectedcount())); } protected void showalertbox() { // todo auto-generated method stub alertdialog.builder builder1 = new alertdialog.builder(notification.this); builder1.setmessage("delete " + adaptor.getselectedids().size()+ " events?"); builder1.setcancelable(true); builder1.seticon(r.drawable.alert); builder1.settitle("caution"); builder1.seticon(android.r.drawable.ic_dialog_alert); builder1.setpositivebutton("yes", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { deletedata(); mactionmode.finish(); } }); builder1.setnegativebutton("no", new dialoginterface.onclicklistener() { public void onclick(dialoginterface dialog, int id) { dialog.cancel(); } }); alertdialog alert11 = builder1.create(); alert11.show(); } protected void copytoclip() { stringbuilder sharetext = new stringbuilder(); (int = 0; < adaptor.getselectedids().size(); i++) { notificationdata data = notificationlist .get(adaptor.getselectedids().keyat(i)); sharetext.append(data.title + " " + data.venue + " " + data.date + " " + data.time); sharetext.append("\n"); } clipboardmanager clipboard = (clipboardmanager) getsystemservice(context.clipboard_service); clipdata clip = clipdata.newplaintext("notification app", sharetext); clipboard.setprimaryclip(clip); toast.maketext(getapplicationcontext(), "data copied clipboard", toast.length_long).show(); } protected void sharedate() { stringbuilder sharetext = new stringbuilder(); (int = 0; < adaptor.getselectedids().size(); i++) { notificationdata data = notificationlist .get(adaptor.getselectedids().keyat(i)); sharetext.append(data.title + " " + data.venue + " " + data.date + " " + data.time); sharetext.append("\n"); } string share = sharetext.tostring(); intent sendintent = new intent(); sendintent.setaction(intent.action_send); sendintent.putextra(intent.extra_text, share); sendintent.settype("text/plain"); startactivity(sendintent); } protected void deletedata() { int count = 0; int startpoint = adaptor.getselectedids().keyat(0); (int = 0; < adaptor.getselectedids().size(); i++) { adaptor.remove(notificationlist.get(startpoint)); count++; } string message = " event"; if(count>1) { message = " events"; } toast.maketext(getapplicationcontext(), count + message+" deleted", toast.length_long) .show(); } private void addtocalender() { try { int count = 0; (int = 0; < adaptor.getselectedids().size(); i++) { notificationdata data = notificationlist .get(adaptor.getselectedids().keyat(i)); contentresolver cr = getapplicationcontext() .getcontentresolver(); contentvalues values = new contentvalues(); string mydate = data.date + " " + data.time; string timearr[] = data.time.split("to"); simpledateformat sfd = new simpledateformat( "' date: 'mm/dd/yyyy 'time: 'hh a", locale.getdefault()); long time = sfd.parse(mydate).gettime(); values.put(calendarcontract.events.dtstart, time); if (timearr.length > 0) { string endtime = timearr[1]; simpledateformat timeformat = new simpledateformat( "' date: 'mm/dd/yyyy hh a", locale.getdefault()); long endtime = timeformat.parse(data.date + " " + endtime) .gettime(); values.put(calendarcontract.events.dtend, endtime); } values.put(calendarcontract.events.title, data.title); values.put(calendarcontract.events.description, data.venue); timezone timezone = timezone.getdefault(); values.put(calendarcontract.events.event_timezone, timezone.getid()); values.put(calendarcontract.events.calendar_id, 1); uri uri = cr .insert(calendarcontract.events.content_uri, values); count++; } string message = " event"; if(count>1) { message = " events"; } toast.maketext(getapplicationcontext(), count + message + " added calender", toast.length_long) .show(); } catch (exception e) { e.printstacktrace(); } } }
check following code / steps
1) add in activity (ui refresh activity)
private broadcastreceiver mmybroadcastreceiver;
then ,
2) in onresume
@override protected void onresume() { // todo auto-generated method stub super.onresume(); mmybroadcastreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { // here can refresh listview or other ui toast.maketext(getapplicationcontext(), "receiver", 2000).show(); } }; try { localbroadcastmanager.getinstance(this).registerreceiver(mmybroadcastreceiver,new intentfilter("your_action")); } catch (exception e) { // todo: handle exception e.printstacktrace(); }}
// , other code
3) unregister in onpause
@override protected void onpause() { // todo auto-generated method stub super.onpause(); localbroadcastmanager.getinstance(this).unregisterreceiver(mmybroadcastreceiver); }
4) add in gcm reciver class. first check activity visible or not using static variable
if visible add intent gcm_rec = new intent("your_action"); localbroadcastmanager.getinstance(arg0).sendbroadcast(gcm_rec); else use notification manager notification.
i think easy , best way refresh listview ui / call fetching method.
Comments
Post a Comment