0

所以,我的代码有两个问题:
1)我希望每个选项卡都保存它的状态。以便 TextView 显示更改的文本(如果已更改)。
2)我无法正确连接/绑定和取消绑定服务到片段

文本必须从服务更改。

请帮忙,我不知道我是如何实现我的意图的。

我的活动.java

package com.example.tabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MyActivity extends Activity {

    private static String ACTION_BAR_INDEX = "ACTION_BAR_INDEX";

    private Tab tTab1;
    private Tab tTab2;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private TabListener<Tab1> tab1Listener;
    private TabListener<Tab2> tab2Listener;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {

                }
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        myServiceIntent = new Intent(this, MyService.class);
        bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
        if (!isServiceRunning()) {
            startService(myServiceIntent);
        }

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);

        tTab1 = actionBar.newTab();

        tab1Listener = new TabListener<Tab1>(this, R.id.fl_main, Tab1.class);

        tTab1.setTag("Tab_1");
        tTab1.setText("Tab_1");
        tTab1.setTabListener(tab1Listener);

        tTab2 = actionBar.newTab();

        tab2Listener = new TabListener<Tab2>(this, R.id.fl_main, Tab2.class);

        tTab2.setTag("Tab_2");
        tTab2.setText("Tab_2");
        tTab2.setTabListener(tab2Listener);

        actionBar.addTab(tTab1, 0);
        actionBar.addTab(tTab2, 1);
    }

    public boolean isServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (MyService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

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

        unbindService(myConnection);
        stopService(myServiceIntent);
    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {

        private Fragment fragment;
        private Activity activity;
        private Class<T> fragmentClass;
        private int fragmentContainer;

        public TabListener(Activity activity, int fragmentContainer, Class<T> fragmentClass) {

            this.activity = activity;
            this.fragmentContainer = fragmentContainer;
            this.fragmentClass = fragmentClass;
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            if (fragment != null) {
                ft.attach(fragment);
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (fragment == null) {
                String fragmentName = fragmentClass.getName();
                fragment = Fragment.instantiate(activity, fragmentName);
                ft.add(fragmentContainer, fragment, fragmentName);
            } else {
                ft.attach(fragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (fragment != null) {
                ft.detach(fragment);
            }
        }

    }

}

我的服务.java

package com.example.tabs;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class MyService extends Service {

    private final IBinder myBinder = new MyBinder();
    private static Handler myServiceHandler;

    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    public void sendMessage(String sText, int id) {

        Bundle bundle = new Bundle();
        bundle.putString("Text" + id, sText);
        Message bundleMessage = new Message();
        bundleMessage.setData(bundle);

        myServiceHandler.sendMessage(bundleMessage);
    }

    public class MyBinder extends Binder {

        public MyService getService() {
            return MyService.this;
        }

        public void setCallbackHandler(Handler myActivityHandler) {
            myServiceHandler = myActivityHandler;
        }

        public void removeCallbackHandler() {
            myServiceHandler = null;
        }
    }
}

Tab1.java

package com.example.tabs;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Tab1 extends Fragment {

    public static String TAG = Tab1.class.getClass().getSimpleName();

    private static TextView tvText;
    private EditText editText;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {
                    tvText.setText(text);
                }
            }
        }
    };


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab1, container, false);



        tvText = (TextView) view.findViewById(R.id.tv_tab1);

        editText = (EditText) view.findViewById(R.id.editText1);

        Button btn1 = (Button) view.findViewById(R.id.btn_change_text_1);

        btn1.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                myService.sendMessage(String.valueOf(editText.getText()), 1);
            }
        });

        return view;
    }


    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        myServiceIntent = new Intent(activity, MyService.class);
        activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {

        super.onDetach();

        getActivity().unbindService(myConnection);
    }
}

Tab2.java

package com.example.tabs;

import android.app.Activity;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Tab2 extends Fragment {

    public static String TAG = Tab2.class.getClass().getSimpleName();

    private static TextView tvText;
    private EditText editText;

    private static MyService.MyBinder myBinder;
    private static Intent myServiceIntent;
    private static MyService myService;

    private static ServiceConnection myConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName name, IBinder binder) {
            myBinder = (MyService.MyBinder) binder;
            myService = myBinder.getService();
            myBinder.setCallbackHandler(myServiceHandler);
        }

        public void onServiceDisconnected(ComponentName name) {
            myService = null;
            myBinder = null;
        }
    };

    /** Callbackhandler. */
    private static Handler myServiceHandler = new Handler() {

        public void handleMessage(Message message) {

            super.handleMessage(message);

            Bundle bundle = message.getData();

            if (bundle != null) {
                String text = bundle.getString("Text1", "");

                if (!text.equals("")) {
                    tvText.setText(text);
                }
            }
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab2, container, false);

        tvText = (TextView) view.findViewById(R.id.tv_tab2);

        editText = (EditText) view.findViewById(R.id.editText2);

        Button btn2 = (Button) view.findViewById(R.id.btn_change_text_2);

        btn2.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                myService.sendMessage(String.valueOf(editText.getText()), 2);
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        myServiceIntent = new Intent(activity, MyService.class);
        activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDetach() {

        super.onDetach();

        getActivity().unbindService(myConnection);
    }

}

主要的.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical" >
    <FrameLayout
    android:id="@+id/fl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>


</LinearLayout>

tab1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_change_text_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Change text" />

    <TextView
        android:id="@+id/tv_tab1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TAB1\nTAB1\nTAB1" />

</LinearLayout>

tab2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btn_change_text_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="Change text" />

    <TextView
        android:id="@+id/tv_tab2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:text="TAB2\nTAB2\nTAB2" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tabs"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="TabsPlusService"
        android:theme="@android:style/Theme.Holo" >
        <activity
            android:name="com.example.tabs.MyActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="TabsPlusService"
            android:theme="@android:style/Theme.Holo" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true" >
        </service>
    </application>

</manifest>
4

1 回答 1

0

所以,我明白了:)



1) 从活动MainActivity.java中删除所有服务代码

package com.example.tabs;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MyActivity extends Activity {

    private Tab tTab1;
    private Tab tTab2;

    private TabListener<Tab1> tab1Listener;
    private TabListener<Tab2> tab2Listener;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);

        tTab1 = actionBar.newTab();

        tab1Listener = new TabListener<Tab1>(this, "tab1", Tab1.class);

        tTab1.setTag("Tab_1");
        tTab1.setText("Tab_1");
        tTab1.setTabListener(tab1Listener);

        tTab2 = actionBar.newTab();

        tab2Listener = new TabListener<Tab2>(this, "tab2", Tab2.class);

        tTab2.setTag("Tab_2");
        tTab2.setText("Tab_2");
        tTab2.setTabListener(tab2Listener);

        actionBar.addTab(tTab1, 0);
        actionBar.addTab(tTab2, 1);
    }

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

    }

    public static class TabListener<T extends Fragment> implements ActionBar.TabListener {

        private Fragment mFragment;
        private Activity activity;
        private Class<T> mFragmentClass;
        private String mTag;

        public TabListener(Activity activity, String mTag, Class<T> fragmentClass) {

            this.activity = activity;
            this.mFragmentClass = fragmentClass;
            this.mTag = mTag;
        }

        public void onTabReselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.attach(mFragment);
            }
        }

        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            if (mFragment == null) {
                mFragment = Fragment.instantiate(activity, mFragmentClass.getName());
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            if (mFragment != null) {
                ft.detach(mFragment);
            }
        }

    }

}


2) 将服务代码添加到 tab1.java & tab2.java

Tab1.java

 package com.example.tabs;

    import android.app.ActivityManager;
    import android.app.ActivityManager.RunningServiceInfo;
    import android.app.Fragment;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.IBinder;
    import android.os.Message;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;

    public class Tab1 extends Fragment {

        public static String TAG = Tab1.class.getSimpleName();

        private static TextView tvText;
        private EditText editText;

        private static MyService.MyBinder myBinder;
        private static Intent myServiceIntent;
        private static MyService myService;

        private static ServiceConnection myConnection = new ServiceConnection() {

            public void onServiceConnected(ComponentName name, IBinder binder) {
                myBinder = (MyService.MyBinder) binder;
                myService = myBinder.getService();
                myBinder.setCallbackHandler(myServiceHandler);
            }

            public void onServiceDisconnected(ComponentName name) {
                myService = null;
                myBinder = null;
            }
        };

        /** Callbackhandler. */
        private static Handler myServiceHandler = new Handler() {

            public void handleMessage(Message message) {

                super.handleMessage(message);

                Bundle bundle = message.getData();

                if (bundle != null) {
                    String text = bundle.getString("Text1", "");

                    if (!text.equals("")) {
                        tvText.setText(text);
                    }
                } 
            }
        };

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.tab1, container, false);

            tvText = (TextView) view.findViewById(R.id.tv_tab1);

            editText = (EditText) view.findViewById(R.id.editText1);

            Button btn1 = (Button) view.findViewById(R.id.btn_change_text_1);

            btn1.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    myService.sendMessage(String.valueOf(editText.getText()), 1);
                }
            });

            return view;
        }

        public void onResume() {
            super.onResume();
            myServiceIntent = new Intent(getActivity(), MyService.class);
            getActivity().bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE);
            if (!isServiceRunning()) {
                getActivity().startService(myServiceIntent);
            }
        }

        public void onPause() {
            super.onPause();
            getActivity().unbindService(myConnection);
        }

public void onDestroy() {
    super.onDestroy();

    if (isServiceRunning()) {
        getActivity().stopService(myServiceIntent);
    }

}

        public boolean isServiceRunning() {
            ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
            for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (MyService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
            return false;
        }
    }


Tab2.java 看起来类似

于 2013-07-01T13:49:16.147 回答