佈局文件未動 java
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() { //一、建立對話框構造器 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(); } } }