Android: Implement Force downline function

Source: Internet
Author: User

Mandatory downline function should be considered more common, a lot of applications have this feature, such as your QQ number in other places to log in, you will be forced to squeeze offline. In fact, the idea of implementing a forced downline function is relatively simple, just need to pop up a dialog box on the interface, so that users can not do anything else, you have to click the OK button in the dialog box, and then go back to the login screen. However, there is a problem, because we are notified that the need to force offline may be in any interface, do you need to write a popup dialog on each interface logic? If you really think so, that's a remote way of thinking, and we can use the broadcast knowledge learned in this chapter to make it very easy. Create a new Broadcastbestpractice project and start doing it.

Forcing the Downline function requires shutting down all activities before returning to the login screen. If your response is fast enough, you should think that we have already implemented the ability to close all activities in the best Practices section of chapter 2nd, so you just need to use the same scenario. Create a Activitycollector class to manage all activities, as shown in the following code:

public class Activitycollector {

public static list<activity> activities = new arraylist<activity> ();

public static void addactivity (activity activity) {

Activities.add (activity);

}

public static void removeactivity (activity activity) {

Activities.remove (activity);

}

public static void Finishall () {

for (Activity activity:activities) {

if (!activity.isfinishing ()) {

Activity.finish ();

}

}

}

}

Then create the Baseactivity class as the parent class for all activities, as shown in the following code:

public class Baseactivity extends Activity {

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate); Activitycollector.addactivity (this);

}

@Override

protected void OnDestroy () {

Super.ondestroy (); Activitycollector.removeactivity (this);

}

}

Then you need to create a login interface layout, remember the login interface we wrote in Section 3.3.4? This is also a direct use of the good, this can save us a lot of kung Fu. Create a new layout file Login.xml, as shown in the following code:

<tablelayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent " android:stretchcolumns= "1" >

<TableRow>

<textviewandroid:layout_height= "Wrap_content" android:text= "account:"/>

<edittextandroid:id= "@+id/account" android:layout_height= "wrap_content" android:hint= "Input youraccount"/>

</TableRow>

<TableRow>

<textviewandroid:layout_height= "Wrap_content" android:text= "Password:"/>

<edittextandroid:id= "@+id/password" android:layout_height= "wrap_content" android:inputtype= "TextPassword"/ >

</TableRow>

<TableRow>

<buttonandroid:id= "@+id/login" android:layout_height= "Wrap_content" android:layout_span= "2" android:text= " Login "/>

</TableRow>

</TableLayout>

The above code is directly re-use before the content of the written good, very happy. But from here on, we need to do it by ourselves. Now that the login interface layout has been completed, then you should go to write the login interface activities, the new loginactivity inherit from Baseactivity, the code is as follows:

public class Loginactivity extends Baseactivity {

Private EditText Accountedit; Privateedittext Passwordedit; Private Button login;

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.login);

Accountedit = (EditText) Findviewbyid (r.id.account);p Asswordedit = (EditText) Findviewbyid (R.id.password); Login = (Button) Findviewbyid (R.id.login); Login.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (View v) {

String account =accountedit.gettext (). toString (); String password =passwordedit.gettext (). toString ();

// If the account is admin and the password is 123456, the login is considered successful

if (account.equals ("admin") && password.equals ("123456")) {Intent Intent = newintent (Loginactivity.this,

Mainactivity.class); startactivity (intent); Finish ();

} else {

Toast.maketext (Loginactivity.this, "account or passwordisinvalid",

}

}

});

}

Toast.length_short). Show ();

}

As you can see, here we simulate a very simple login feature. First use the Setcontentview () method to load the login layout and call the Findviewbyid () method to get an instance of the Account entry box, the Password entry box, and the login button, respectively. Then the login button in the Click event to face the input account and password to determine, if the account is admin and password is 123456, it is believed that login success and jump to mainactivity, otherwise prompt user account or password error.

Therefore, you can think of mainactivity as a successful login to enter the main interface of the program, here we do not need to provide in the main interface what fancy features, only need to join the mandatory downline function can be, modify the code in the Activity_main.xml, as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "match_parent" >

<buttonandroid:id= "@+id/force_offline" android:layout_width= "match_parent" android:layout_height= "Wrap_ Content "android:text=" Send forceoffline broadcast "/>

</LinearLayout>

Very simple, just a button. Then modify the code in the mainactivity as follows:

public class Mainactivity extends Baseactivity {

@Override

protected void OnCreate (bundlesavedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

Button Forceoffline = (button) Findviewbyid (r.id.force_offline);

Forceoffline.setonclicklistener (New Onclicklistener () {

@Override

public void OnClick (VIEWV) {

Intent Intent = new Intent ("Com.example.broadcastbestpractice. Force_offline ");

Sendbroadcast (Intent);

}

});

}

}

It's also very simple, but here's the point where we send a broadcast in the button's Click event, the broadcast value is Com.example.broadcastbestpractice.FORCE_OFFLINE, and the broadcast is for the notification program strong

The user is offline. That is, the logic of forcing users to go offline is not written in the mainactivity, but should be written in the radio receiver to receive the broadcast, so that the function of forcing the downline will not be attached to any interface, whether in the program anywhere, only need to issue such a broadcast, You can complete the forced downline operation.

Then there is no doubt that next we need to create a broadcast receiver, the new Forceofflinereceiver

Inherited from Broadcastreceiver, the code looks like this:

public class Forceofflinereceiver extends Broadcastreceiver {

@Override

Public Voidonreceive (Final context context, Intent Intent) {Alertdialog.builder Dialogbuilder = new Alertdialog.builder ( Context);d Ialogbuilder.settitle ("Warning");

Dialogbuilder.setmessage ("forced to be offline. Trytologin again. ");

Dialogbuilder.setcancelable (FALSE);

Dialogbuilder.setpositivebutton ("OK",Newdialoginterface.onclicklistener () {

@Override

public void OnClick (Dialoginterface dialog, int which) {

Activitycollector.finishall ();// Destroy all activities

Intent Intent = newintent (context,loginactivity.class);

}

Intent.addflags (Intent.flag_activity_new_task);

context.startactivity (intent);// restart LoginAc ti v it y

});

Alertdialog Alertdialog = Dialogbuilder.create ();

// You need to set the type of Alertdialog to ensure that it pops up properly in the broadcast receiver

Alertdialog.getwindow (). SetType (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

Alertdialog.show ();

}

}

This time the OnReceive () method can no longer just pop up a Toast, but add more code, then we will take a closer look at it. The first thing is to use Alertdialog.builder to build a dialog box, note that it is important to call the Setcancelable () method to set the dialog box to be non-canceled, or the user can press the back key to close the dialog box to continue to use the program. Then use the Setpositivebutton () method to register the dialog box with the OK button when the user

When you click the OK button, call Activitycollector's Finishall () method to destroy all activities and restart the loginactivity activity. In addition, since we are in the broadcast receiver to start the activity, so be sure to add flag_activity_new_task this flag to Intent. Finally, you need to set the dialog box type to Type_system_alert, or it will not pop up in the broadcast receiver.

In this case, all the logic for forcing the downline is complete, and then we need to androidmanifest.xml

File to configure the code as follows:

<manifestxmlns:android= "Http://schemas.android.com/apk/res/android" package= "Com.example.broadcastbestpractice" android:versioncode= "1"

Android:versionname= "1.0" >

<uses-sdkandroid:minsdkversion= "android:targetsdkversion="/>

<uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/>

<applicationandroid:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" >

<activityandroid:name= ". Loginactivity "android:label=" @string/app_name ">

<intent-filter>

<action android:name= "Android.intent.action.MAIN"/>

<category android:name= "Android.intent.category.LAUNCHER"/>

</intent-filter>

</activity>

<activity android:name= ". Mainactivity ">

</activity>

<receiver android:name= ". Forceofflinereceiver ">

<intent-filter>

<actionandroid:name= "Com.example.broadcastbestpractice. Force_offline "/>

</intent-filter>

</receiver>

</application>

</manifest>

Here are a few things to note, first because we have a system-level dialog box in Forceofflinereceiver, so we have to declare Android.permission.SYSTEM_ALERT_WINDOW permissions. Then register the loginactivity, and set it as the main activity, because certainly not let the user start the program directly into the Mainactivity bar. Finally, register the Forceofflinereceiver and designate it to receive the Com.example.broadcastbestpractice.FORCE_OFFLINE broadcast.

OK, now try to run the program, the first will go to the login interface, and you can enter the account number and password here, 5.10.

Figure 5.10

If you enter the account is admin, password is 123456, click the login button will go to the main interface of the program, as shown in Figure 5.11.

Figure 5.11

Then click the Send radio button, will issue a forced offline broadcast, Forceofflinereceiver received this broadcast will pop up a dialog box prompting the user has been forced offline, 5.12 shown.

At this point the user will no longer be able to manipulate any element of the interface, only click on the OK button and then return to the logging interface. In this way, the mandatory downline function has been fully implemented.

Android: Implement Force 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.