Android development steps: 20: network settings

Source: Internet
Author: User

Android development steps: 20: network settings
Network settings are very important in mobile apps, because applications generally need to interact with external networks. This article demonstrates a classic application scenario. For example, I recently developed a transfer application. This requires interaction with the network. After the user opens the application, the application first determines whether the user has enabled the wifi or gprs network. If not, the system will jump to the wireless and network settings page of the system. After the user is set up, I made a more user-friendly process and created a broadcast receiver, as we know, when a mobile phone opens the network or receives a text message, it will publish a broadcast. Once the network is connected, my broadcast receiver receives the information and determines whether the current transfer application is in the enabled status. After the application is enabled, it automatically jumps to the transfer application. This means that you can re-open the application, removing the need to disable the previous re-open operation of the application. Okay. Let's start our experiment.
Create a network operation class NetWorkUtil. java

Package com. snda. wallet. utils;
Import android. app. Activity;
Import android. app. AlertDialog;
Import android. content. Context;
Import android. content. DialogInterface;
Import android. content. Intent;
Import android.net. ConnectivityManager;
Import android.net. NetworkInfo;
Import android. OS. Vibrator;

Import com. snda. wallet. R;

/**
*

Network Settings


* @ Author zhuzhifei
*/
Public class NetWorkUtil {
Public NetWorkUtil (){

}

/**
* Determine whether the network is connected
*
* @ Param context
* @ Return
*/
Public static boolean checkNetworkStatus (Context context ){
ConnectivityManager connectivityManager = (ConnectivityManager) context
. GetSystemService (Context. CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager. getActiveNetworkInfo ();
Return (activeNetInfo = null )? False: true;
}
/**
* A prompt box is displayed to inform the user that the network is not connected. Click settings to go to the network settings page. Click Cancel to close the dialog box.
* @ Param context
*/
Public static void showNetWorkStatus (final Context context ){
AlertDialog. Builder builder = new AlertDialog. Builder (context );
Builder. setTitle ("prompt message"). setMessage (R. string. network_confirm). setCancelable (false)
. SetPositiveButton (R. string. yes, new DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int id ){
Intent intent = new Intent (android. provider. Settings. ACTION_WIRELESS_SETTINGS );
Context. startActivity (intent );
}
}). SetNegativeButton (R. string. cancel, new DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog, int id ){
Dialog. cancel ();
}
}). Show ();
Vibrator vibrator = (Vibrator) context. getSystemService (Context. VIBRATOR_SERVICE );
Vibrator. vibrate (new long [] {5, 12, 9, 19},-1 );
}

}
Remember to add permissions




Create a network status broadcast receiver NetWorkStateReceiver. java

/**
*
*/
Package com. snda. wallet. network;

Import java. util. List;

Import android. app. ActivityManager;
Import android. app. ActivityManager. RunningTaskInfo;
Import android. content. BroadcastReceiver;
Import android. content. Context;
Import android. content. Intent;
Import android.net. ConnectivityManager;
Import android.net. NetworkInfo;
Import android.net. NetworkInfo. State;
Import android. widget. Toast;

Import com. snda. wallet. tabs. TransferMainActivity;
Import com. snda. wallet. utils. LogUtils;

/**
* Network status broadcast Receiver
* @ Author zhuzhifei
*
*/
Public class NetWorkStateReceiver extends BroadcastReceiver {

Private String tag = "NetWorkStateReceiver ";

/*
* The broadcast receiver receives the broadcast that the mobile phone has connected to the network.
*/
@ Override
Public void onReceive (Context context, Intent intent ){
// TODO Auto-generated method stub
// Determine the network status
NetworkInfo info = intent
. GetParcelableExtra (ConnectivityManager. EXTRA_NETWORK_INFO );
State state = info. getState ();
LogUtils. I (tag, "type:" + info. getType ());
LogUtils. I (tag, "state:" + state );
// Add another identifier to determine that the current application is open.
String MY_PKG_NAME = "com. snda. wallet ";
Boolean isAppRunning = false;
ActivityManager am = (ActivityManager) context
. GetSystemService (Context. ACTIVITY_SERVICE );
List List = am. getRunningTasks (100 );
For (RunningTaskInfo task: list ){
// If (task. topActivity. getPackageName (). equals (MY_PKG_NAME)
// & Task. baseActivity. getPackageName (). equals (MY_PKG_NAME ))
If (task. baseActivity. getPackageName (). equals (MY_PKG_NAME )){
IsAppRunning = true;
Break;
}
}
// If the current application is enabled and connected to wifi or 3G network, the application homepage is displayed.
If (isAppRunning ){
Switch (state ){
Case CONNECTED:
Intent intentnew = new Intent (context,
TransferMainActivity. class );
Intentnew. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK );
Context. startActivity (intentnew );
Break;
Case CONNECTING:
Toast. makeText (context, "the network is being connected. You will be logged on automatically later", Toast. LENGTH_SHORT)
. Show ();
Break;
Case DISCONNECTED:
Toast. makeText (context, "the network is not connected. Please connect to the Internet first", Toast. LENGTH_SHORT)
. Show ();

Break;
Case DISCONNECTING:
Toast. makeText (context, "the network is losing connection. Please note", Toast. LENGTH_SHORT)
. Show ();
Break;
Default:
Break;
}
}
// Determine the network type
// Switch (info. getType ()){
// Case ConnectivityManager. TYPE_MOBILE:
// Break;
// Case ConnectivityManager. TYPE_WIFI:
// Break;
//}

}

}
Remember to add permissions and register the broadcast receiver.

Android: name = ". MyApplication" android: theme = "@ style/Theme. Spm">





The application homepage calls network operations to determine the network status

@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. transfer_main );
If (NetWorkUtil. checkNetworkStatus (TransferMainActivity. this) = false) // if no network connection is available, the system first prompts you to connect to the Internet.
{
NetWorkUtil. showNetWorkStatus (TransferMainActivity. this );
Return;
}
......
}

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.