Interaction between notification and Activity

Source: Internet
Author: User
Overview

Notification is an information notification method that is displayed on the top of the mobile phone to notify the user without affecting the user's operations. You can also use the drop-down notification operation drawer to notify the user, implement communication between notifications and activities, notifications, and services. For example, a notification communicates with an activity. An activity sends a notification (create a notification) through the notificationmanager, and an action in a drawer notification transmits information by sending a broadcast event, at this time, as long as the activity has registered the receiver of the broadcast event, it can receive the notification information, so as to realize notification and activity interaction.

Example (synchronous music playing and paused for notifications and activities)
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >            <FrameLayout android:layout_width="match_parent"        android:layout_height="match_parent">                <ImageView android:layout_width="match_parent"            android:layout_height="match_parent"            android:src="@drawable/bg"            android:scaleType="fitXY"/>                <ImageView             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@drawable/play_over"            android:layout_gravity="center"            android:clickable="true"            android:id="@+id/imageView"            android:background="@drawable/img_bg"/>            </FrameLayout>        </LinearLayout>

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="64dp"    android:background="#e0e0e0"    android:orientation="horizontal">        <ImageView         android:id="@+id/imageView1"        android:layout_width="64dp"        android:layout_height="64dp"        android:src="@drawable/sc"/>        <RelativeLayout         android:layout_width="match_parent"        android:layout_height="match_parent">                      <ImageView         android:id="@+id/image_control"        android:clickable="true"        android:padding="4dp"        android:layout_alignParentLeft="true"        android:layout_centerVertical="true"        android:layout_width="48dp"        android:layout_height="48dp"        android:src="@drawable/play_over"/>                        <TextView            android:id="@+id/tv_title"             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_toRightOf="@id/image_control"            android:padding="4dp"            android:text="Sweet Child O' Mine"            android:singleLine="true"            android:textAppearance="?android:attr/textAppearanceMedium"/>              <TextView          android:id="@+id/tv_nowTime"           android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_toRightOf="@id/image_control"            android:text="00:00"            android:layout_alignParentBottom="true"/>            <TextView          android:id="@+id/tv_totallTime"           android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_alignParentBottom="true"            android:text="00:00"/>                    </RelativeLayout>    </LinearLayout>


Package COM. liujun. activity; import Java. text. simpledateformat; import Java. util. date; import Java. util. timer; import Java. util. timertask; import COM. liujun. liujunmusicnotification. r; import android. app. activity; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingintent; import android. content. broadcastreceiver; import android. content. context; import android. cont Ent. intent; import android. content. intentfilter; import android. media. mediaplayer; import android. OS. bundle; import android. support. v4.app. notificationcompat; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. imageview; import android. widget. remoteviews; public class mainactivity extends activity {private mediaplayer; // Media Player private Icationicationmanager notificationmanager; // notification manager private imageview; // play music picture button private Boolean isplaying = false; // whether the music is being played // The intent is public static final string playmusic_intent = "playmusic_intent"; public static final string pausemusic_intent = "pausemusic_intent "; // notification ID idpublic static final int notification_id = 1; // time timer private timer; private mybroadcastrecever recever; @ overrideprotected void oncr Eate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. mian_activity); // instantiate Media Player mediaplayer = mediaplayer. create (this, R. raw. SC); // instantiate the notification manager icationicationmanager = (notificationmanager) This. getsystemservice (icationication_service); timer = new timer (); imageview = (imageview) This. findviewbyid (R. id. imageview); imageview. setonclicklistener (onclicklistener); // register the broadcast event inte sent in the receiving notification bar Ntfilter intentfilter = new intentfilter (); intentfilter. addaction (pausemusic_intent); intentfilter. addaction (playmusic_intent); recever = new mybroadcastrecever (); this. registerreceiver (recever, intentfilter);} onclicklistener = new onclicklistener () {@ overridepublic void onclick (view v) {If (! Isplaying) {// No music is played // start playing playmusic (); // change the image background imageview. setimageresource (R. drawable. pause_over); // change the flag isplaying = true;} else {// playing the music... // pause the playing of the music pausemusic (); // change the image background imageview. setimageresource (R. drawable. play_over); // change the flag isplaying = false;} // send the notification bar activitysendnotification () ;};/*** play music */protected void playmusic () {If (mediaplayer = NULL) {mediaplayer = mediaplayer. create (mainactivity. this, R. raw. SC);} If (Timer = NULL) {timer = new timer ();} // enable the timer task. Every second, the drawer is updated to notify the music playing progress timer. schedule (New mytimertask (), 0, 1000); // play the music mediaplayer. start () ;}// time task, update drawer notification, and playback progress (Note: New is required for each call) private class mytimertask extends timertask {@ overridepublic void run () {// activitysendnotification () ;}/ *** send notification */protected void activitysendnotification () {// notification builder icationicationicationcompat. builder = new notificationcompat. buil Der (this); // set the small icon builder. setsmallicon (R. drawable. favorite); // load the custom remote layout remoteviews remoteview = (remoteviews) New remoteviews (this. getpackagename (), R. layout. my_notification); // setting cannot pull cancel drawer notification builder. setongoing (true); // set the title remoteview. settextviewtext (R. id. TV _title, "Sweet Child o 'Mine"); // current playback time (Note: exit the interface when playing music on the interface, instead of exiting the interface when paused, the mediaplayer may be released and left empty when the program executes the // ondestroy () method. The code segment is in the subthread and does not exit with the main thread synchronously, // The result is med. If (mediaplayer = NULL) {return;} date currentdate = new date (mediaplayer. getcurrentposition (); // total duration date totaldate = new date (mediaplayer. getduration (); simpledateformat = new simpledateformat ("mm: SS"); // sets the current playback time progress remoteview. settextviewtext (R. id. TV _nowtime, simpledateformat. format (currentdate); // sets the total length of the Song remoteview. settextviewtext (R. id. TV _totalltime, simpledateformat. forma T (totaldate); log. I ("liujun", "Whether to play music: --" + isplaying); If (isplaying) {// playing music // display can pause the picture remoteview. setimageviewresource (R. id. image_control, R. drawable. pause_over);} else {// display the remoteview picture that can be played. setimageviewresource (R. id. image_control, R. drawable. play_over);} // notification bar, interactive icationicationtoactivity (remoteview, isplaying); // load view layout builder. setcontent (remoteview); // create Notification = builder. build ();// Send notification icationicationmanager. Y (ication_id _id, notification);}/*** notification bar Interactive Activity * @ Param isplaying */private void notificationtoactivity (remoteviews remoteview, Boolean isplaying) {intent = new intent (); if (isplaying) {// playing music... // try to pause playing intent. setaction (pausemusic_intent); // modify the image remoteview. setimageviewresource (R. id. image_control, R. drawable. pause_over);/* // update flag isplaying = false; */} else {// no music playing // try Play the intent music. setaction (playmusic_intent); // modify the image remoteview. setimageviewresource (R. id. image_control, R. drawable. play_over); // * // update flag isplaying = true; * // send broadcast, update activitypendingintent pendingintent = pendingintent. getbroadcast (this, 0, intent, pendingintent. flag_update_current); remoteview. setonclickpendingintent (R. id. image_control, pendingintent);} // broadcast receiver (broadcast events that receive notifications) private class mybroadcastrecever extends Broadcastreceiver {@ overridepublic void onreceive (context, intent) {If (intent. getaction () = playmusic_intent) {// play the music on the notification end // play the music playmusic (); // whether to play the playing symbol isplaying = true; // change the image flag imageview. setimageresource (R. drawable. pause_over);} else if (intent. getaction () = pausemusic_intent) {// pause the music on the notification end // pause the music pausemusic (); // whether to play the playing music mark isplaying = false; // change the image flag imageview. setimageresource (R. drawable. play_ove R);} // update the activity information above, and then send a notification activitysendnotification () ;}/ *** pause playing music */protected void pausemusic () {If (mediaplayer! = NULL & mediaplayer. isplaying () {mediaplayer. Pause () ;}// suspend sending notification if (timer! = NULL) {timer. cancel (); timer = NULL ;}@ overrideprotected void ondestroy () {super. ondestroy (); this. unregisterreceiver (recever); // release the resource if (mediaplayer! = NULL) {mediaplayer. Release (); mediaplayer = NULL;} // whether to notify icationmanager. Cancel (icationication_id );}}



Interaction between notification and Activity

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.