如何在没有网络连接时调用新布局?

时间:2011-08-08 19:34:07

标签: android android-layout android-activity connection android-manifest

好的,这是我的问题:

当没有互联网连接时,我将开始新的活动,但新的活动屏幕是黑色的。新活动应显示ImageView ...

检查连通性并开始新的活动:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
    if (!info.isConnected()) {
    }
}
else {
    startActivity(new Intent(main.this, no_connection.class));
}

NO_CONNECTION ACTIVITY:

    package com.hello.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class no_connection extends Activity {


        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.connection_error);
            ImageView image = (ImageView) findViewById(R.id.image_verkkovirhe);

      }
}

此处是CONNECTION_ERROR布局:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
  android:id="@+id/connection_error" 
  android:fitsSystemWindows="true" android:orientation="vertical">



        <ImageView 
        android:src="@drawable/verkkovirhe" 
        android:layout_width="fill_parent" 
        android:id="@+id/image_verkkovirhe" 
        android:layout_height="fill_parent" 
        android:clickable="false" 
        android:fitsSystemWindows="true" 
        android:visibility="visible"></ImageView>


    </RelativeLayout>

OR

也许我只能在没有网络连接的情况下更改布局?当我尝试这个时,我会强行关闭?

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null) {
        if (!info.isConnected()) {
        }
    }
    else {
        setContentView(R.layout.connection_error );
    }

1 个答案:

答案 0 :(得分:1)

如果要从服务启动新活动,则应使用FLAG_ACTIVITY_NEW_TASK标志。它应该是这样的:

Intent intent = new Intent(main.this, no_connection.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);