当前位置: 首页 > 面试题库 >

如何从片段访问服务功能,该片段绑定到Android中的父级活动?

锺离良哲
2023-03-14
问题内容

我有一个带有Viewpager片段的Android活动。在活动的onCreate方法中,我将服务绑定到该服务,该服务始终在后台运行。

在片段中,在特定条件下,我需要在处理该条件的服务中调用一个函数。访问服务并调用其功能的正确方法是什么?

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = "MainActivity";

DbHelper dbHelper;
SessionManager sessionManager;
SessionCache sessionCache;
Map<String, ?> userDetails;
protected SocketListener socketService;

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


    sessionManager = new SessionManager(getApplicationContext());

    // Connect to background socketlistener service
    Intent serviceIntent = new Intent(MainActivity.this, SocketListener.class);
    startService(serviceIntent);
    .
    .
    .

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.profileicon)));
    tabLayout.addTab(tabLayout.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.homeicon)));
    tabLayout.addTab(tabLayout.newTab().setText("").setIcon(getResources().getDrawable(R.drawable.chaticon)));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    final NonSwipeableViewPager viewPager = (NonSwipeableViewPager) findViewById(R.id.view_pager);

    final CustomPagerAdapter pagerAdapter = new CustomPagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(pagerAdapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    viewPager.setCurrentItem(1);
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
}

    private ServiceConnection serviceConnection = new ServiceConnection() {


@Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        socketService = ((SocketListener.LocalBinder) iBinder).getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        socketService = null;
    }
};

}

这是我的服务。我连接到服务器,并不断收听更新。

SocketListener.java

    package com.example.gopa2000.mobapps;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class SocketListener extends Service {

private static String TAG = "SocketListener";
private Socket socket;

public SocketListener() { }

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return localBinder;
}

private final IBinder localBinder = new LocalBinder();
public class LocalBinder extends Binder {
    public SocketListener getService(){
        Log.i(TAG, "getService: Sitting in local binder.");
        return SocketListener.this;
    }

    public void sendMessage(String message){
        socket.emit("match", message);
    }
}

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

public void isBoundable(){
    Log.i(TAG, "Bind like a baller.");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    Runnable connect = new ConnectSocket();
    new Thread(connect).start();
    return START_STICKY;
}

class ConnectSocket implements Runnable {
    @Override
    public void run() {
        try {
            socket = IO.socket(RESTClient.getURL());

            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    Log.i(TAG, "call: Connected to backend!");
                }
            });

            socket.connect();
        } catch (URISyntaxException e){
            Log.e(TAG, "run: ", e);
        }
    }
}

public Socket getSocket(){
    return this.socket;
}
}

这是我需要调用的片段sendMessage(string)

public class MainViewFragment extends Fragment {

private final String TAG = "MVFragment";

private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private SessionManager sessionManager;
private ArrayList<CustomCard> cards;
private CardAdapter cardAdapter;
private Button btn;
private SwipeFlingAdapterView flingContainer;
private Map<String, ?> userDetails;
// hax
private static String userEmail;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.from(getContext()).inflate(R.layout.fragment_main_view, container, false);

            .
            .

    flingContainer.setAdapter(adapter);

    flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener(){
            .
            .

        @Override
        public void onRightCardExit(Object o) {
            .
            .

            if(match){

            // need to call sendMessage from the service here. <------------------------

                sessionCache.addToMatchTable(Liker, Likee);
            }
        }

        @Override
        public void onAdapterAboutToEmpty(int i) {

        }

        @Override
        public void onScroll(float v) {

        }
    });


    flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener(){
        @Override
        public void onItemClicked(int itemPosition, Object dataObject){
            Toast.makeText(getActivity(), "Clicked!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity().getApplicationContext(), FullScreenCardLayout.class);
            startActivity(intent);
        }
    });

    return view;
}

问题答案:

首先方法sendMessage(message)应该在服务内部而不是LocalBinder类中

public class SocketListener extends Service {

    public void sendMessage(String message){
        socket.emit("match", message);
    }
}

其次从片段访问活动方法,您应该在片段内部创建接口

interface MessageSender {
    void sendMessage(String message);
}

然后在您的活动中实施

public class MainActivity extends AppCompatActivity implements MessageSender {

    @Override
    public void sendMessage(String message) {
        // call the service here
        socketService.sendMessage(message);
    }
}

在片段中,实现onAttach()并初始化接口实例

public class MainViewFragment extends Fragment {
    private MessageSender mMessageSenderCallback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
         try {
            mMessageSenderCallback = (MessageSender) context;
        } catch (ClassCastException e) {
            // Error, class doesn't implement the interface
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        // Remove activity reference
        mMessageSenderCallback = null;
    }
}

要发送消息,请mMessageSenderCallback.sendMessage(message)在片段内调用消息。



 类似资料:
  • 这是我的场景: 我在我的活动中有ViewPager,其中包含6个片段。我用手指滑动来禁用分页,所以每当我想滑动时,我使用相关的按钮和: 在每一个swipe片段中(swipe完成后),我希望向服务器发送一个GET请求,并获取一些数据并在该片段中显示它。因为这样做: 答:Daniel Nugent的代码运行良好,除了在发送GET请求时显示ProgressDialog之外,我使用了: 这段代码也返回Nu

  • 我想将数据从父片段传递到选项卡式片段(子片段),以便传递初始数据(当父片段第一次加载时),我使用了Bundle数据。当在子片段的嵌套片段中时,我调用PopbackStack(),以便通过单击按钮返回。在那里,我需要更新之前传递到子选项卡片段的捆绑数据。捆绑数据不会得到更新的数据集 父片段-初始状态 子片段-Tab片段 孩子- 我错过了什么?请帮忙

  • //使用startActivity(intent)也不起作用//无论我做什么,应用程序都会崩溃

  • 我是Android开发的新手,我在将firebase auth从SignInActivity传递到HomeFragment上有一个问题。代码是这样的 公共类SignInActivity扩展AppCompatActivity } 这是HomeFragment片段 公共类HomeFragment扩展Fragment{ } 这是logcat 致命异常:主进程:clouwiko.dev.prasiku,P

  • 问题内容: 我托管了5个片段,在每个片段上我都需要填写一些字段。 我想从中获取这些字段的值。我尝试了类似的东西: AddActivity.java FragPagerAdapter.java OtherFragment.java 公共类OtherFragment扩展Fragment {Button btn; 更新 的问题我总是得到EditText(而其他字段要获得)的问题等于null如果它们位于片