Broadcast practice--forcing user downline function

Source: Internet
Author: User

Basic knowledge of broadcasting see my article http://blog.csdn.net/jdfkldjlkjdl/article/details/43017091

Below is an example of a mandatory user line. For reference only.


Forcing the Downline function requires shutting down all activities before returning to the login screen.

1. First create a project Broadcastbestpractice, and a new Activitycontroller class,

Package Com.example.broadcastbestpractice;import Java.util.arraylist;import Java.util.list;import android.app.activity;/** * @ClassName: Activitycontroller * @Description: This class is used to manage all activities * @author Xzy * @date 2015-1-22 a.m. 9:1 2:48 *  */public class Activitycontroller {public static list<activity> activities = New arraylist<activity& gt; ();p ublic static void addactivity (activity activity) {Activities.add (activity);} public static void removeactivity (activity activity) {activities.remove (activity);} public static void Finishall () {(Activity activity:activities) {if (!activity.isfinishing ()) {Activity.finish ()}}}}

2. Create Baseactivity as the parent class for all activities.

Package Com.example.broadcastbestpractice;import android.app.activity;import android.os.bundle;/** * @ClassName: Baseactivity * @Description: Build parent class for all activities * @author Xzy * @date 2015-1-22 a.m. 9:18:18 *  */public class Baseactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Activitycontroller.addactivity (this);} @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); Activitycontroller.removeactivity (this);}}

3. Create a login interface layout file Login.xml, the main implementation of the function, the interface is very simple.

<?xml version= "1.0" encoding= "Utf-8"? ><tablelayout xmlns:android= "http://schemas.android.com/apk/res/     Android "Android:layout_width=" Match_parent "android:layout_height=" Match_parent "android:stretchcolumns=" 1 "> <TableRow> <textview android:layout_height= "wrap_content" android:text= "account:            "/> <edittext android:id=" @+id/accountedit "android:layout_height=" Wrap_content " Android:hint= "Input your account"/> </TableRow> <TableRow> <textview android oid:layout_height= "Wrap_content" android:text= "Password:/> <edittext android:id=" @+id /passwordedit "android:layout_height=" wrap_content "android:inputtype=" Textpassword "/> </T ablerow> <TableRow> <button android:id= "@+id/login" android:layout_height= "WR Ap_content "Android:layouT_span= "2" android:text= "Login"/> </TableRow></TableLayout> 


4. Write the login activity Loginactivity.java, and let it inherit from Baseactivity.java.

Package Com.example.broadcastbestpractice;import Android.content.intent;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import android.widget.toast;/** * @ClassName: loginactivity * @Description: Login activity * @author Xzy * @ Date 2015-1-22 a.m. 9:37:44 * */public Final class Loginactivity extends Baseactivity {private EditText Etaccount,etpass;pri Vate Button btnlogin; @Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.login); etaccount = (EditText) Findviewbyid ( R.id.accountedit); etpass = (EditText) Findviewbyid (r.id.passwordedit); btnlogin = (Button) Findviewbyid (R.id.login); Btnlogin.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method stubstring account = Etaccount.gettext (). toString (); String password = Etpass.gettext (). toString ();//Analog Login IF (account.equals ("Xu") && password.equals ("123")) {Intent Intent = new Intent (Loginactivity.this, Mainactivity.class); startactivity (intent); Finish ();} Else{toast.maketext (Getapplicationcontext (), "Login Failure", Toast.length_long). Show ();}});}}

The mainactivity mentioned above can be understood as the program's main interface after the successful login process, where we do not need very fancy features, only need to add mandatory downline function in mainactivity. So modify Activity_main.xml to add a button

5. Modify the Activity_main.xml file

<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 "    android:paddingbottom= "@dimen/activity_vertical_margin"    android:paddingleft= "@dimen/activity_ Horizontal_margin "    android:paddingright=" @dimen/activity_horizontal_margin "    android:paddingtop=" @dimen /activity_vertical_margin "    tools:context=". Mainactivity ">    <button        android:id=" @+id/force_offline "        android:layout_width=" Match_parent "        android:layout_height= "wrap_content"        android:text= "Send Force offline broadcast"/></ Relativelayout>

6. Modify the Mainactivity code to implement the Force downline function in this code

Package Com.example.broadcastbestpractice;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.view.menu;import Android.view.view;import Android.view.View.OnClickListener; Import android.widget.button;/** * @ClassName: mainactivity * @Description: Mandatory downline activity * @author Xzy * @date 2015-1-22 morning 9:52:3 0 * */public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {SUPER.ONCR Eate (savedinstancestate); Setcontentview (R.layout.activity_main); Button Btnforceoffline = (button) Findviewbyid (r.id.force_offline); Btnforceoffline.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method stub// Dynamically registering a broadcast--you need to create a broadcast receiver to receive the broadcast intent intent = new Intent ("Com.example.broadcastbestpractice.FORCE_OFFLINE"); Sendbroadcast (intent);}});} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}} <strong></strong>
The above program is very simple, but one of the main points is that we send a broadcast in the button, the value of the broadcast is Com.example.broadcastbestpractice.FORCE_OFFLINE, this broadcast is used to notify the program to force the user offline. That is to say that the mandatory user Downline program is not unloaded mainactivity, but should be written in the receiver receiving the broadcast, so that the function of forcing the downline will not be attached to any interface, regardless of the program's interface, as long as the transmission of such a broadcast, you can complete the forced offline operation. Name no doubt, next we need to create a broadcast receiver.

7. New receiver Forceofflinereceiver, inherited from Broadcastreceiver

Package Com.example.broadcastbestpractice;import Android.app.alertdialog;import Android.content.BroadcastReceiver ; Import Android.content.context;import Android.content.dialoginterface;import Android.content.intent;import android.view.windowmanager;/** * @ClassName: Forceofflinereceiver * @Description: Broadcast receiver * @author Xzy * @date 2015-1-22 a.m. 9 : 57:59 * */public class Forceofflinereceiver extends Broadcastreceiver {@Overridepublic void onreceive (Final Context cont Ext, Intent Intent) {//TODO auto-generated method Stubalertdialog.builder Dialogbuilder = new Alertdialog.builder (Contex T);d ialogbuilder.settitle ("Warning");d ialogbuilder.setmessage ("You is forced to be offline. Try to login again. "); Dialogbuilder.setcancelable (False);d Ialogbuilder.setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@ overridepublic void OnClick (dialoginterface dialog, int which) {//TODO auto-generated method stub// Destroy all activities Activitycontroller.finishall (); Intent Intent = new Intent (Context,loginacTivity.class);//Start the activity in the broadcast receiver, so be sure to add the following logo to intent. Intent.addflags (Intent.flag_activity_new_task); context.startactivity (intent);}); Alertdialog Alertdialog = dialogbuilder.create ()///The type of the alertdialog needs to be set to ensure that the Alertdialog.getwindow () is ejected normally in the broadcast receiver. SetType (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); Alertdialog.show ();}} <strong></strong>
This time the OnReceive () method can no longer just pop up a toast, but add more code, first use Alertdialog.builder to build a dialog box, note that this must be called setcancelable () Method sets the dialog box to not be canceled, or the user presses the back key to close the dialog box and continue to use the program. Then use the Setpositivebutton () method to register the dialog with the OK button, and when the user taps the OK button, call Activitycontroller's Finishall () method to destroy all activities. and restart loginactivity This activity, in addition, because we start the activity in the broadcast receiver, because must give intent to join Flag_activity_new_task this sign. Finally, set the dialog box to Type_system_alert, or it will not pop up in the broadcast receiver. In this case, all the logic of forcing the downline is basically done, and then we need to configure the Androidmanifest.xml file.


8. Configuring the Androidmanifest.xml File

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.broadcastbestpractice "android:versioncode=" 1 "android:versionname=" 1.0 "> &L T;USES-SDK android:minsdkversion= "8" android:targetsdkversion= "/><span style=" color: #cc0000; "        ><uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/></span> <application Android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android Oid:theme= "@style/apptheme" > <activity android:name= "Com.example.broadcastbestpractice.LoginActiv ity "android:label=" @string/app_name "> <intent-filter> <action android:n            Ame= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name= "Com.example.broadcastbestpractice.MainActivity" > </activity> <span style= "color: #cc0000;" > <receiver android:name= ". Forceofflinereceiver "> <intent-filter> <action android:name=" com.example.broadcastbe Stpractice. Force_offline "/> </intent-filter> </receiver></span> &LT;/APPLICATION&G T;</manifest>

The above configuration files need to be noted: 1. Because a system-level dialog box pops up in Forceofflinereceiver, you must declare Android.permission.SYSTEM_ALERT_WINDOW permissions, It then registers the loginactivity, sets it as the primary activity, and then registers the Forceofflinereceiver and specifies that it receives the broadcastbestpractice. Force_offline the radio.


Program Source code: HTTP://PAN.BAIDU.COM/S/1I3W0F57




Broadcast practice--forcing user downline function

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.