接收从socket到Fragment的响应

时间:2014-08-20 14:11:11

标签: android android-fragments broadcastreceiver android-service

有许多类似的问题,但我没有设法找到一个与我的情况相符的问题,所以在这里。我有一个服务,它接收数据并使用广播接收器将数据发送回活动。当我使用使用支持Android API 8及更高版本的标签视图设置的活动(使用App Compat Library)时,会出现问题。我成功地从Fragment类向服务发送请求,这是通过按布局文件中的一个按钮完成的,该按钮仅用于活动中的选定选项卡并链接到java类。但是,我初始化的广播接收器不会从服务中捕获广播。我目前的代码显示在下面。

片段类

public class ConfigFragmentGeneral extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
EditText dsi, dsimaxd, dsimind, dsmaxa, dsiis, adc1diff, adc2diff, adc3diff, adc4diff, adc1level, adc2level, adc3level, adc4level;
Button send, save, delete;
Spinner presetSpinner;
View fragmentView;

ArrayAdapter<String> presetAdapter;
List<String> presetArray, presetNamesArray;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fragmentView = inflater.inflate(R.layout.fragment_config_general, container, false);

    ..........

    return fragmentView;
}

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.sendGeneral:

            if (isAllowedToSave())
            {
                  ///////////Intent to the Service
                final String confValues ="some values";

                OtherActivity.socketIntent = new Intent(getActivity(), SocketService.class);
                OtherActivity.socketIntent.putExtra("type", 12);
                OtherActivity.socketIntent.putExtra("config_values", confValues);
                getActivity().startService(Pagrindinis.socketIntent);
            }

            break;

显示选项卡式片段的活动,BroadcastReceiver也在这里

public class Config extends ActionBarActivity{
ActionBar actionBar;
private ViewPager viewPager;

static boolean mBound = false;
static SocketService mService;

public static final String RECEIVE_SET_CONFIG = "something.whatever";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_config);

    actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    viewPager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fragmentManager = getSupportFragmentManager();

    ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener()
    {
        public void onPageSelected(int position)
        {
            super.onPageSelected(position);
            actionBar.setSelectedNavigationItem(position);
        }
    };

    viewPager.setOnPageChangeListener(pageChangeListener);

    PagerAdapter pagerAdapter = new PagerAdapter(fragmentManager);
    viewPager.setAdapter(pagerAdapter);
    actionBar.setDisplayShowTitleEnabled(true);

    ActionBar.TabListener tabListener = new ActionBar.TabListener()
    {
        @Override
        public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
        {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}

        @Override
        public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
    };

    Tab tab = actionBar.newTab()
            .setText("One Tab")
            .setTabListener(tabListener);

    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText("Another Tab")
            .setTabListener(tabListener);

    actionBar.addTab(tab);
}

@Override
public void onBackPressed()
{
    super.onBackPressed();
    overridePendingTransition(R.anim.slide_right_in,R.anim.slide_left_out);
}

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

    unbindService(mConnection);
    unregisterReceiver(broadcastReceiver);
    mBound = false;
}

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

    Pagrindinis.socketIntent = new Intent(this, SocketService.class);
    bindService(Pagrindinis.socketIntent, mConnection, Context.BIND_AUTO_CREATE);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("RECEIVE_SET_CONFIG");
    registerReceiver(broadcastReceiver, intentFilter);
    mBound = true;

    Log.v("DEV","onResume");
}

public static ServiceConnection mConnection = new ServiceConnection()
{
    @Override
    public void onServiceConnected(ComponentName name, IBinder service)
    {
        SocketService.SocketBinder binder = (SocketService.SocketBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name)
    {
        mBound = false;
    }
};

public static BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().equals(RECEIVE_SET_CONFIG))
        {
            Log.v("DEV", "CONFIG RESPONSE BROADCAST RECEIVER");

            //Toast.makeText(this, intent.getExtras().getString("response"), Toast.LENGTH_SHORT).show();
        }
    }
};

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.config, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_settings)
    {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

套接字类线程

else if ((temp.equals("somecase")) && ((type == 12)))
                    {
                        StringTokenizer extraFilter = new StringTokenizer(filterToken.nextToken(),":");
                        if (extraFilter.hasMoreTokens()) temp = extraFilter.nextToken();

                        if (temp.equals(something))
                        {
                            temp = extraFilter.nextToken();

                            Intent ret = new Intent();
                            ret.setAction(Config.RECEIVE_SET_CONFIG);
                            ret.putExtra("response", temp);
                            sendBroadcast(ret);

                            Log.v("DEV","forwarded SET CONFIG");
                        }
                    }

我还尝试将广播接收器(与onStart和onStop一起)移动到Fragment类,但实现了相同的结果。任何想法如何我可以访问从片段类中的Socket发送的广播?或者我可能不是以正确的方式从Socket发送广播?谢谢

0 个答案:

没有答案