嗨我有我的aacplayer应用程序,但是当我断开所有连接时我的意思是wifi +移动数据并尝试打开应用程序崩溃没有打开,我想要做的是在主要活动中向用户显示消息喜欢:Theres没有连接,请再试一次。
我的应用是这样的:
我有一个列表视图然后从xml我加载许多广播电台的数据然后当我点击其中一个打开aac播放器并正确播放。我也用它来传输服务。
如何避免应用程序崩溃?
继承我的主要活动:
public class Principal extends Activity {
protected TextView title;
protected ImageView icon;
static final String URL = "http://www.streaming507.com/estaciones.xml";
static final String KEY_ESTACION = "estacion";
static final String KEY_ID = "id";
static final String KEY_NOMBRE = "nombre";
static final String KEY_WEB = "web";
static final String KEY_SHOUTCAST = "shoutcast";
static final String KEY_MINIATURA = "miniatura";
static final String KEY_LOGO = "logo";
private static final int DIALOG_ALERT = 10;
public static Activity handleToClose;
ListView list;
LazyAdapter adapter;
private Button botonactualizar;
public void actualizar() {
title = (TextView) findViewById(R.id.title);
icon = (ImageView) findViewById(R.id.icon);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ESTACION);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NOMBRE, parser.getValue(e, KEY_NOMBRE));
map.put(KEY_WEB, parser.getValue(e, KEY_WEB));
map.put(KEY_SHOUTCAST, parser.getValue(e, KEY_SHOUTCAST));
map.put(KEY_MINIATURA, parser.getValue(e, KEY_MINIATURA));
map.put(KEY_LOGO, parser.getValue(e, KEY_LOGO));
songsList.add(map);
}
list = (ListView) findViewById(R.id.list);
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String url = ((TextView) view.findViewById(R.id.shoutcast))
.getText().toString();
String logo = ((TextView) view.findViewById(R.id.logo))
.getText().toString();
try {
stopService(new Intent(view.getContext(), MyService.class));
} catch (Exception ex) {
}
Intent myIntent = new Intent(view.getContext(),
AACPlayerActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
myIntent.putExtra("URL", url);
myIntent.putExtra("LOGO", logo);
startActivity(myIntent);
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.window_title);
handleToClose = this;
actualizar();
botonactualizar = (Button)findViewById(R.id.botonactualizar);
botonactualizar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View vw) {
actualizar();
Toast.makeText(Principal.this, "Lista de estaciones actualizada",
Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu_opciones1, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_actualizar:
actualizar();
Toast.makeText(Principal.this, "Lista de estaciones actualizada",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_salir:
showDialog(DIALOG_ALERT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ALERT:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Desea salir de la aplicacion?");
builder.setCancelable(true);
builder.setPositiveButton("Si", new OkOnClickListener());
builder.setNegativeButton("No", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onCreateDialog(id);
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
finish();
stopService(new Intent(Principal.this, MyService.class));
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(1);
}
}
}
我知道有一些叫做连接管理器,但我不知道我必须在我的主要活动或流服务中设置它,所以当我打开没有互联网的应用程序时,我可以看到一条消息:请再试一次。然后一个刷新按钮,所以如果互联网开启,那么我可以从网页加载xml列表。
谢谢。编辑:
当我打开没有互联网连接的应用程序时出现此错误
ava.net.UnknownHostException: Unable to resolve host "www.mydomain.com": No address associated with hostname
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.spoledge.aacplayer/com.spoledge.aacplayer.Principal}: java.lang.NullPointerException
答案 0 :(得分:1)
在Activity
...
private boolean isConnected() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
在onResume()
内的Activity
内或在您想要开始播放之前的任何时间进行调用。
答案 1 :(得分:0)
我修复此问题,将此代码添加到我的主要活动中:
public boolean isOnline() {
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
try {
if (connectionManager.getActiveNetworkInfo().isConnected()) {
Log.d("ConStatus", "Data Connection On");
return true;
} else {
Log.d("ConStatus", "Data Connection off");
return false;
}
} catch (NullPointerException e) {
// No Active Connection
Log.i("ConStatus", "No Active Connection");
return false;
}
}
然后oncreate:
} else {
Log.d("Connection Status", "Connection Not Available");
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("No hay conexion a internet disponible");
alertDialog.setMessage("La conexion a Internet es necesaria para el uso de esta aplicacion.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
finish();
}
});
alertDialog.show();
}
} catch(NullPointerException e){
Log.d("Connection Status", "Connection Not Available");
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("No hay conexion a internet disponible");
alertDialog.setMessage("La conexion a Internet es necesaria para el uso de esta aplicacion.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
finish();
}
});
alertDialog.show();
}
}
现在可以运行,在活动开始之前检查连接并在用户未连接到互联网然后关闭活动时显示一个对话框。
谢谢