android开发步步为营之20:网络设置

        网络设置这块在手机应用里面是非常重要的一块,因为一般应用都需要和外部网络做交互的。本篇文章就展示了一个比较经典应用场景。比如我最近在开发的转账应用。这个是需要和网络交互的。当用户打开应用之后,应用首先会判断用户是否已经打开wifi或者gprs网络。没有则跳转到系统的无线和网络设置界面,当用户设置好了之后,我这里做了一个更人性化的处理,创建了一个广播接收器,因为我们知道,手机在打开网络或者收到短信的时候,都会对外发布一条广播。一旦网络连接上了之后,我的这个广播接收器,就会收到信息,然后判断当前的转账应用是否是打开的状态,打开了之后,就自动跳转到转账应用。等于帮用户重新打开了应用了,免去用户关闭之前的应用重新打开的操作了。好,下面开始我们的实验。
             新建网络操作类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;
 
/**
 * <p>网络设置类</p>
 * @author zhuzhifei
*/
public class NetWorkUtil {
    public NetWorkUtil() {
 
    }
 
    /**
     * 判断网络是否连通
     *
     * @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;
    }
    /**
     * 弹出提示框,告知用户当前没有连接网络,点设置跳转到网络设置页面,点取消关闭对话框
     * @param context
     */
    public static void showNetWorkStatus(final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("提示信息").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);
    }
 
}
注意记得加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
             新建网络状态广播接收器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;
 
/**
 * 网络状态广播接收器
 * @author zhuzhifei
 *
 */
public class NetWorkStateReceiver extends BroadcastReceiver {
 
         private String tag = "NetWorkStateReceiver";
 
         /*
          * 广播接收器,接收手机已经连上网络的广播
          */
         @Override
         public void onReceive(Context context, Intent intent) {
                   // TODO Auto-generated method stub
                   //判断网络状态
                   NetworkInfo info = intent
                                     .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                   State state = info.getState();
                   LogUtils.i(tag, "type:" + info.getType());
                   LogUtils.i(tag, "state:" + state);
                   // 再加一个判断当前应用是打开的
                   String MY_PKG_NAME = "com.snda.wallet";
                   boolean isAppRunning = false;
                   ActivityManager am = (ActivityManager) context
                                     .getSystemService(Context.ACTIVITY_SERVICE);
                   List<RunningTaskInfo> 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;
                            }
                   }
                   //如果当前应用是打开的,连上wifi或者3g网络时,跳转到应用首页
                   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, "网络正在连接,稍等将为您自动登录", Toast.LENGTH_SHORT)
                                                        .show();
                                     break;
                            case DISCONNECTED:
                                     Toast.makeText(context, "网络没有连接,请您先联网", Toast.LENGTH_SHORT)
                                                        .show();
 
                                     break;
                            case DISCONNECTING:
                                     Toast.makeText(context, "网络正在失去连接,请您注意", Toast.LENGTH_SHORT)
                                                        .show();
                                     break;
                            default:
                                     break;
                            }
                   }
                   //判断网络类型
                   // switch (info.getType()) {
                   // case ConnectivityManager.TYPE_MOBILE:
                   // break;
                   // case ConnectivityManager.TYPE_WIFI:
                   // break;
                   // }
 
         }
 
}
注意记得加权限及注册广播接收器
<uses-permission android:name="android.permission.GET_TASKS" />
    <application android:icon="@drawable/icon" android:label="@string/app_name"
       android:name=".MyApplication" android:theme="@style/Theme.Spm">
       <receiver android:name=".network.NetWorkStateReceiver">
           <intent-filter>
              <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
           </intent-filter>
       </receiver>
             应用首页调用网络网络操作类判断网络状态
 
@Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.transfer_main);
       if(NetWorkUtil.checkNetworkStatus(TransferMainActivity.this)==false)//没有联网,则先提示用户联网
       {
           NetWorkUtil.showNetWorkStatus(TransferMainActivity.this);
           return;
       }
         ……
    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。