Android Activity生命周期应用 网络设置

布局文件未动

package com.pas.checknetwork;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity
{

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void onStart()
	{
		//1、创建对话框构造器
		checkNetState();
		super.onStart();
	}
	private void checkNetState()
	{
		ConnectivityManager connmanager = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);

		NetworkInfo netinfo = connmanager.getActiveNetworkInfo();
		if (netinfo != null && netinfo.isConnected())
		{
			Toast.makeText(this, "网络可用", Toast.LENGTH_LONG).show();
		} else
		{
			AlertDialog.Builder builder=new Builder(this);
			builder.setTitle("提醒");
			builder.setMessage("当前网络不可用,点击确定设置网络");
			builder.setPositiveButton("取消",new OnClickListener()
			{
				
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					finish();
				}
			});
			builder.setNegativeButton("确定", new OnClickListener()
			{
				
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					Toast.makeText(MainActivity.this, "网络不可用,请设置", Toast.LENGTH_LONG).show();
					Intent intent = new Intent();
					intent.setClassName("com.android.settings", "com.android.settings.SettingsEMUI");
					startActivity(intent);
				}
			});
			builder.create().show();
		}
	}
}

 

你可能感兴趣的:(Android Activity生命周期应用 网络设置)