0

嗨,我有我的 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);
        }
    }
}

我知道有一个叫做connectivitymanager的东西,但我不知道在我的主要活动或流服务中我必须在哪里设置它,所以当我在没有互联网的情况下打开应用程序时,我可以看到一条消息:请重试。然后是一个刷新按钮,所以如果互联网打开,那么我可以从网页的 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
4

2 回答 2

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您想要开始流式传输之前或任何时间从内部调用它。

于 2012-10-26T01:13:47.897 回答
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;
        }
    }

然后创建:

} 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();
                }
    }

现在可以工作了,在活动开始之前它会检查连接并在用户未连接到互联网时显示一个对话框,然后关闭活动。

谢谢你

于 2012-10-26T16:36:40.830 回答