【问题标题】:Started Service and fragment lifecycle启动服务和片段生命周期
【发布时间】:2015-03-15 16:18:02
【问题描述】:

这是我今天的第二个疑问-.- 我有一个问题。 我有一个加载片段的 mainactivity,并且在 mainactivity 的 oncreate 中启动了一项服务。

在我的片段中,通过 mainactivity 中的一个侦听器,我调用了我的服务的一个函数。

问题是:当片段调用服务功能时,服务没有启动。

我该怎么办?

我的服务向调用片段中正确方法的 mainactivity 发送消息。

我没有解决这个问题的想法。 .也许我太累了..

也许我能知道片段何时完全加载!有办法知道吗?也许如果我在片段的 onStart() 中调用某个函数?

这是mainactivity的代码

public class ConnectionHandle extends Activity implements interfaceinthefragment
{

boolean mBound;
Service mService;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
fragment fragment;

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

    //In this point we start the service 
    Intent intent = new Intent(this, servicetostart.class);
    startService(intent);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    //We load the correct fragment 
    fragmenttoload = new fragmenttoload();
    fragmentManager = getFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragmenttoload);
    fragmentTransaction.commit();
}


private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) 
    {
        // TODO Auto-generated method stub
        // Because we have bound to an explicit
        // service that is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.
         mBound = true;
         LocalBinder binder = (LocalBinder) service;
         mService = binder.getService();
         mService.setHandler(serviceHandler);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) 
    {
        // TODO Auto-generated method stub
         mBound = false;
    }

};

 private Handler serviceHandler = new Handler(Looper.myLooper()) 
    {
        @Override
        public void handleMessage(Message msg) 
        {
            someF(msg);
        }
    };


    private void someF(Message msg)
    {

        //In this place I set something in the fragment depending of arrives  messages from the service

    }


   //function in the interface inside fragment
    @Override
    public void startSearch() 
    {
        if(mBound) 
            //function in the service
    }

    .

现在是代码片段:

// onAttach
@Override
public void onAttach(Activity activity) 
{
    super.onAttach(activity);
    try 
    {
         discoverListener = (Listener) activity;
    } 
    catch (ClassCastException e) 
    {
        throw new ClassCastException(activity.toString()+" must implement Listener");
    }
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    if (vwParent != null) 
    {
        ViewGroup parent = (ViewGroup) vwParent.getParent();
        if (parent != null)
            parent.removeView(vwParent);
    }
    try 
    {
            vwParent=inflater.inflate(R.layout.layoutx,container,false);

    } catch (InflateException e) {

    }

    return vwParent;
}

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

    firstScan=true;
    deviceName = new ArrayList<xxx>(); 
    adapter=new adapter.....

    vwParent.findViewById(R.id.xx).setVisibility(View.INVISIBLE);
    vwParent.findViewById(R.id.xx).setVisibility(View.VISIBLE);
    vwParent.findViewById(R.id.xx).setVisibility(View.INVISIBLE);
     //interface implemented by the mainactivity
    **discoverListener.startSearch();**
    ListView listView = (ListView) vwParent.findViewById(R.id.listView1);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(this);

}

Bold 中的函数 (discoverListener.startSearch();) 在服务真正启动之前被调用并且它不起作用:/

我想在 mainactivity 中而不是在每个片段中处理来自服务的消息。我错了吗?

编辑:也许用更好的英语 我要做的是:从片段调用服务内部的一个函数,通过 mainactivity 中实现的函数 interfaceinthefragment.startSearch()。然后服务执行一些操作并通过消息将结果提供给 mainactivity。此活动检查函数 someF(msg) 中的结果消息并在片段内执行一些函数。

【问题讨论】:

  • 您需要发布代码以便其他人了解您在做什么。 Service 生命周期不直接与 ActivityFragment 生命周期绑定。
  • 现在我添加一张我要做的事情的图片:)
  • 使用 IntentService 怎么样
  • 为什么在我的情况下 intentservice 更好?使用“正常”服务我不能做我想做的事?我有两项活动附加到这项服务,我希望我不必改变一切

标签: android android-fragments android-activity android-service


【解决方案1】:

如果您想在服务中调用方法,请通过调用 startService() 来实现...然后检查服务中的意图 onStartCommand() 并决定调用哪个方法。您可以根据需要随时调用 startService。这是一个例子。

我在应用程序类中有这个

startService(new Intent(mContext, LocationMonitorService.class));

这在我的服务中:

public int onStartCommand(Intent intent, int flags, int startId) {
        MyLog.p(this,"inside service making request for location updates");
        mIntent = intent;
        if (intent != null) {
            if (intent.hasCategory("COM.GMAIL.NPNSTER.FIRST_PROJECT.MAP_FRAGMENT_RESUMED")) {
                startRequestMarkerUpdates();    
                startLocationPushRequests();
            } else if (intent.hasCategory("MAP_FRAGMENT_PAUSED")) {
                endRequestMarkerUpdates();
                endLocationPushRequests();
                } else if (intent.hasCategory("LOCATION_UPDATE_REQUEST_RECEIVED")) {
                deviceLocationClient.requestLLocationUpdates();
            }
        }

只要确保 Fagment 已满载,请覆盖 Fragment 的 onResume 方法。

【讨论】:

  • 谢谢。我会做的是:
  • 谢谢。我要做的是:从片段调用服务内部的函数。该服务执行一些操作并通过消息将结果提供给 mainactivity。此活动检查函数 someF(msg) 中的结果消息并在片段内执行一些函数。
【解决方案2】:

在第一篇文章中,我添加了代码。 我要做的是:从片段调用服务内部的一个函数,通过在主要活动中实现的fragment.startSearch() 中的函数接口。然后在服务内部,做一些操作,并通过消息将结果传递给mainactivity。 MainActivity 使用函数 someF(msg) 检查结果消息,并根据结果调用片段内的正确方法并执行一些操作。

我希望你能帮我理解我能做什么:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    相关资源
    最近更新 更多