Android Actionbar Tabs + Fragments + Service
Posted
by
Vladimir
on Stack Overflow
See other posts from Stack Overflow
or by Vladimir
Published on 2013-07-01T10:20:11Z
Indexed on
2013/07/01
10:20 UTC
Read the original article
Hit count: 888
So, I have 3 problems with my code:
1) I want that each tab saves its state. So that a TextView shows changed text if it was changed.
2) if I go to Tab2 then to Tab1 I can't see the content of the fragments. Only if I touch on the already selected tab, it shows me the content
3) I can't correctly connect/bind and unbind service to Fragment
Text must be changed from Service.
Please help, I don't know how I realize my intent.
MyActivity.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);
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sp = getPreferences(Activity.MODE_PRIVATE);
int actionBarIndex = sp.getInt(ACTION_BAR_INDEX, 0);
getActionBar().setSelectedNavigationItem(actionBarIndex);
}
protected void onSaveInstanceState(Bundle outState) {
// Save the current Action Bar tab selection
int actionBarIndex = getActionBar().getSelectedTab().getPosition();
SharedPreferences.Editor editor = getPreferences(Activity.MODE_PRIVATE).edit();
editor.putInt(ACTION_BAR_INDEX, actionBarIndex);
editor.apply();
// Detach each of the Fragments
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (tab2Listener.fragment != null) {
ft.detach(tab2Listener.fragment);
}
if (tab1Listener.fragment != null) {
ft.detach(tab1Listener.fragment);
}
ft.commit();
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// Find the recreated Fragments and assign them to their associated Tab
// Listeners.
tab1Listener.fragment = getFragmentManager().findFragmentByTag(Tab1.class.getName());
tab2Listener.fragment = getFragmentManager().findFragmentByTag(Tab2.class.getName());
// Restore the previous Action Bar tab selection.
SharedPreferences sp = getPreferences(Activity.MODE_PRIVATE);
int actionBarIndex = sp.getInt(ACTION_BAR_INDEX, 0);
getActionBar().setSelectedNavigationItem(actionBarIndex);
super.onRestoreInstanceState(savedInstanceState);
}
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.detach(fragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.detach(fragment);
}
}
}
}
MyService.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);
}
}
main.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" >
</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>
© Stack Overflow or respective owner