获取方向开关或离开应用程序时的视图

时间:2011-03-11 13:58:54

标签: android android-manifest screen-orientation

我对这个Android编程很陌生。但我正在尝试创建一个从基于Web的服务器接收内容的应用程序 - 这个功能最终就像魅力一样。

但是,有几天我试图找到一个答案,为什么我的应用程序想要记住它在方向切换上的视图,当视图改变为另一个活动或离开应用程序时。

我知道要使用清单文件和捆绑包,但似乎我没有正确实现此功能。

这是我的清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.getpublished.onskelisten"
    android:versionCode="1"
    android:versionName="1.0" 
    android:installLocation="preferExternal">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Onskelisten"
            android:label="@string/app_name" 
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".AboutOnskelisten" 
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
        </activity>
        <activity android:name=".HandleLogin" 
            android:label="@string/app_name" 
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="portrait">
        </activity>
        <activity android:name=".TabHome" 
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
        </activity>
        <activity android:name=".TabWishes" 
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
        </activity>
        <activity android:name=".TabWishlists"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
        </activity>
        <activity android:name=".Register" 
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="sensor"
            android:configChanges="keyboardHidden|orientation">
        </activity>
        <activity android:name=".UserNotLoggedInOptions" 
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar"
            android:screenOrientation="portrait">
        </activity>
    </application>
</manifest>

这是“主要类.Onskelisten”,其中还包括标签:

package com.getpublished.onskelisten;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TabHost;

public class Onskelisten extends TabActivity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ( checkForExtStorage( this ) ) {

            Session.loadConfig( getSharedPreferences(Session.PREFS_NAME, 0 ) );

            if ( Session.checkToken() == false ) {

                startLogin();

            } else {

                startLoggedInSession( );

            }

        } else {

            finish();

        }

        //Session.setNewToken( getSharedPreferences( Session.PREFS_NAME, 0 ) );

    }

    public void startLogin () {

        Session.setNewToken( getSharedPreferences(Session.PREFS_NAME, 0), "", 0);

        Intent intent = (Intent) new Intent( this, UserNotLoggedInOptions.class);
        startActivity(intent);

    }

    private void startLoggedInSession () {

        setContentView(R.layout.tabhost);

        Resources res = getResources();
        TabHost tabHost = getTabHost();
        TabHost.TabSpec spec;
        Intent intent;

        intent = new Intent().setClass( this, TabHome.class);
        spec = tabHost.newTabSpec("home").setIndicator( "Home",
                          res.getDrawable(R.drawable.tab_home))
                          .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass( this, TabWishes.class);
        spec = tabHost.newTabSpec("wishes").setIndicator( "Wishes",
                          res.getDrawable(R.drawable.tab_wishes))
                          .setContent(intent);
        tabHost.addTab(spec);

        intent = new Intent().setClass( this, TabWishlists.class);
        spec = tabHost.newTabSpec("wishlists").setIndicator( "Lists",
                          res.getDrawable(R.drawable.tab_wishlists))
                          .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTabByTag("home");

    }

    public static void addNotification ( int noteId, int contentHeaderId, int contentTextId, Context context, Object className) {

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);

        int icon = R.drawable.icon32;
        String tickerTextString = (String) context.getString(contentHeaderId);
        CharSequence tickerText = (CharSequence) tickerTextString;
        long when = System.currentTimeMillis();

        Notification notification = new Notification(icon, tickerText, when);

        String contentString = (String) context.getString(contentTextId);
        CharSequence contentText = (CharSequence) contentString;
        Intent notificationIntent = new Intent(context, (Class<?>) className );
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, tickerText, contentText, contentIntent);

        mNotificationManager.notify(1, notification);

    }

    @Override
    public void onResume () {
        super.onResume();

        if ( Session.checkToken() == true ) {

            startLoggedInSession( );

        }else {

            startLogin( );

        }

    }

    public static boolean checkForExtStorage ( Context context ) {

        if ( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == false ) {
            Session.showUsertip( "External storage is missing", context );
            return false;
        }

        return true;

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.log_out_token:
            startLogin( );
            return true;
        case R.id.goto_about:
            Intent intent = (Intent) new Intent( getApplicationContext(),AboutOnskelisten.class);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.lowerpopupmenu, menu);
        return true;
    }

    @Override 
    public void onSaveInstanceState (Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);


    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);


    }

    @Override
    public void onPause () {
        super.onPause();

    }

    @Override
    protected void onStop(){
       super.onStop();

    }

}

这是从我的服务器加载内容的“home-tab-class,.TabHome”。 (正如我所提到的;它有效,但是当我离开标签的活动时,它会失去视野。)

package com.getpublished.onskelisten;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TabHome extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        renderHomeScreen( );

    }

    private void renderHomeScreen ( ) {

        Session.loadConfig( getSharedPreferences(Session.PREFS_NAME, 0 ) );

        LinearLayout mainView = (LinearLayout) new LinearLayout(this);
        mainView.setId(1);
        mainView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        ViewGroup hScrollView = null;

        try {
            hScrollView = getLastContentFromWWW();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("TabHome/getLastContentFromWWW", "" + e.getMessage());
        }

        mainView.addView( hScrollView );
        setContentView(mainView);

    }

    @Override
    public void onResume() {
        super.onResume();

        renderHomeScreen( );

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);


    }

    @Override 
    public void onSaveInstanceState (Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);

    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

    }

    private ViewGroup getLastContentFromWWW ( ) throws Exception {

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("Token", Session.TOKEN ));
        postParameters.add(new BasicNameValuePair("GetImages", "Y") );
        postParameters.add(new BasicNameValuePair("Last", "10") );
        postParameters.add(new BasicNameValuePair("Size", "100x100") );

        HorizontalScrollView ScrollView = new HorizontalScrollView( this );
        ScrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        ScrollView.setId(2);
        ScrollView.setBackgroundResource(R.drawable.panelbg);

        TableLayout scrollWrapper = (TableLayout) new TableLayout(this);
        scrollWrapper.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
        scrollWrapper.setId(3);

        LinearLayout scrollChildHead = (LinearLayout) new LinearLayout(this);
        scrollChildHead.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        scrollChildHead.setId(4);

        TableRow scrollChildContent = (TableRow) new TableRow(this);
        scrollChildContent.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        scrollChildContent.setId(5);

        TextView scrollHeader = new TextView(this);
        scrollHeader.setText(R.string.last_images_from_site);
        scrollHeader.setTextSize(20);
        scrollHeader.setId(6);

        scrollChildHead.addView(scrollHeader);

        scrollWrapper.addView(scrollChildHead);


        String response = null;

        // TODO: Fetch locally stored images?

        /**
         * QUERY:
         * http://onskelisten.getpublished.no/Mobile/MobileApps/
         * ?Platform=Android
         * &Version=V1.0
         * &Token=*static*
         * &LastContent=Y
         */

        if ( response == null ) {

            try {
                response = CustomHttpClient.executeHttpPost(postParameters);
                Log.i("Response/getWWW", response);
                JSONGetServerResults.validateResponse(response, this, getSharedPreferences(Session.PREFS_NAME, 0));
            } catch ( Exception e ) {
                e.printStackTrace();
                Log.e("CustomHttpClient.executeHttpPost/JSONGetServerResults.validateResponse", "" + e.getMessage());
            }

        }

        JSONObject lastContentObj = null;
        JSONArray lastContentObjPics = null;

        try {

            lastContentObj = JSONGetServerResults.createNewObject( response );

        } catch ( Exception e ) {
            e.printStackTrace();
            Log.e("lastContentObj/lastContentObj1", "" + e.getMessage());
        }

        if ( lastContentObj.has( "LastImages") )
            lastContentObjPics = lastContentObj.getJSONArray( "LastImages" );

        for ( int i = 0; i < lastContentObjPics.length(); i++ ) {

            Bitmap bitmapFromURL = null;

            try {

                bitmapFromURL = CustomHttpClient.getImageBitmap(lastContentObjPics.getJSONObject(i).getString("EntPic"));

            } catch ( Exception e ) {
                e.printStackTrace();
                Log.e("CustomHttpClient.getImageBitmap", "" + e.getMessage());
            }

            if ( bitmapFromURL != null ) {

                ImageView newImage = (ImageView) new ImageView(this);
                newImage.setContentDescription(lastContentObjPics.getJSONObject(i).getString("EntName"));
                newImage.setMinimumHeight(100);
                newImage.setMinimumWidth(100);
                newImage.setMaxHeight(100);
                newImage.setMaxWidth(100);
                newImage.setClickable(true);
                newImage.setPadding(10, 10, 10, 10);
                newImage.setBackgroundResource(R.drawable.bg_100x100_w_border);
                newImage.setId( i + 100 );

                newImage.setImageBitmap(bitmapFromURL);

                final int newId = (int) new Integer( lastContentObjPics.getJSONObject(i).getString("EntId"));

                newImage.setOnClickListener( new View.OnClickListener() {

                    public void onClick(View v) {
                        Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://onskelisten.getpublished.no/Show/Entry/" + newId + "/"));
                        startActivity(browserIntent);

                    }
                });

                scrollChildContent.addView(newImage);
            }

        }

        scrollWrapper.addView(scrollChildContent);
        ScrollView.addView(scrollWrapper);

        return ScrollView;


    }

}

以及从服务器保存信息的“Session类”,因此应用程序可以接收所需的内容。

package com.getpublished.onskelisten;
import java.io.Serializable;
import java.util.Calendar;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;


public class Session {

    public static final String PREFS_NAME = "Onskelisten";
    public static String TOKEN;
    public static long TOKENLIFETIME;
    public static long TOKENCHECKEDNOW;
    public static boolean TOKENCHECK;

    public static Serializable LastImages;

    public static void setNewToken ( SharedPreferences settings, String token, long tokenLifetime ) {

        // SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString( "Token", token ).commit();
        editor.putLong( "TokenLifetime", tokenLifetime ).commit();

        loadConfig( settings );

        checkToken();

    }

    public static void loadConfig ( SharedPreferences settings ) {

        Session.TOKEN = settings.getString("Token", "");
        Session.TOKENLIFETIME = settings.getLong("TokenLifetime", 0);

        checkToken();

    }

    public static boolean checkToken () {

        Calendar timestampC = (Calendar) Calendar.getInstance();
        Session.TOKENCHECKEDNOW = (timestampC.getTimeInMillis() / 1000);

        if ( Session.TOKEN == "" || Session.TOKENCHECKEDNOW > Session.TOKENLIFETIME )
            Session.TOKENCHECK = false;
        else
            Session.TOKENCHECK = true;

        /*String tokenString = "Token: " + TOKEN;
        tokenString += "\nTokenLifetime " + TOKENLIFETIME;
        tokenString += "\nTokenChecked: " + TOKENCHECKEDNOW;
        tokenString += "\nTokenCheck: " + ( TOKENCHECK == false ? "FALSE" : "TRUE" );

        Toast.makeText( getContext(), tokenString, Toast.LENGTH_SHORT).show();*/

        return Session.TOKENCHECK;
    }

    public static void showUsertip ( CharSequence charSequence, Context context ) {

        Toast.makeText( context, charSequence, Toast.LENGTH_LONG).show();

    }

}

编辑:我删除了一些代码,看起来应用程序现在可以在屏幕方向上完美运行。更新了代码。但不幸的是,离开应用程序时仍然存在问题。

1 个答案:

答案 0 :(得分:0)

您可能必须将应用程序状态保存在文件/数据库中,或者作为活动/应用程序首选项中的键值对保存,并在读取这些值后重新初始化您的活动。当活动重定向或活动结束()时,Android不会自动保存状态。