【问题标题】:Starting service from a fragment从片段开始服务
【发布时间】:2013-08-21 12:00:01
【问题描述】:

我在从片段启动服务时遇到问题。服务已启动,但未在前台显示,我不知道为什么将 isCancelled 变量设置为 true(因此未处理 doInBackground 任务) .

当我从 FragmentActivity 启动它时,它可以工作:startService(new Intent(this, Recorder.class));。但是,当我尝试从 Fragment getActivity().startService(new Intent(getActivity(), Recorder.class)); 启动它时,它并没有按预期工作(如上所述)。

Recorder.class:

public class Recorder extends Service {

boolean isCancelled = false;


@Override
public IBinder onBind(Intent intent) {
    return null;
}


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

    Log.v("service","started");
    Intent intent1 = new Intent(this, MainActivity.class);
    intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification noti = new NotificationCompat.Builder(this)
            .setContentTitle("Recorder")
            .setContentText("running")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pendIntent)
            .setPriority(Notification.PRIORITY_MIN)
            .build();

    startForeground(12345, noti);


    new RecordTask().execute("http://path");

    return START_STICKY;
}

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

   isCancelled = true;
}

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


private class RecordTask extends AsyncTask<String, Void, Boolean> {
    protected Boolean doInBackground(String... StringUrls) {

     // do something
                Log.v("isCancelled", String.valueOf(isCancelled));  
                   // <-- why isCancelled = true?
                if (isCancelled) break;  

            }


        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        }

       return true;
    }

    protected void onProgressUpdate(Integer... progress) {

    }

    protected void onPostExecute(Boolean result) {

    }
  }

}

AddNewRecordFragment:

public class AddNewRecordFragment extends Fragment implements View.OnClickListener {

//   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setRetainInstance(true);
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.addnewrecordfragment, container, false);

    Button b = (Button) v.findViewById(R.id.button);
    Button b2 = (Button) v.findViewById(R.id.button2);
    b.setOnClickListener(this);
    b2.setOnClickListener(this);
    return v;


}


@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button:
            Log.v("start ", "clicked");
            getActivity().startService(new Intent(getActivity(), Recorder.class));

        case R.id.button2:

            getActivity().stopService(new Intent(getActivity(), Recorder.class));

            break;
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.v("fragment", "onAttach");
}

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

    Log.v("fragment", "onDetach");
}

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

    Log.v("fragment", "onDestroy");
  }
}

【问题讨论】:

  • 你在片段类中从哪里开始?在使用 GetActivity() 之前,您必须确保已创建活动并且正确附加了片段。不然就不行了!

标签: android android-fragments android-asynctask android-service


【解决方案1】:

您的问题与从fragment 启动service 无关。如果您将 isCancelled 设置为 true 的唯一时间是在 onDestroy 中,那么服务将按照您的意图启动,它也会在您的 AsyncTask 完成之前被杀死。看看this post。在某些情况下可以终止服务。问题是为什么会调用onDestroy。如果你在它自己的进程上运行这个service,那么service 可能会被杀死,因为你所做的只是设置一个AsyncTask。如果这与托管活动在同一进程上运行,则不完全清楚为什么要调用onDestroy(通常是因为系统需要内存,但在这种情况下我不知道这是否属实)。

【讨论】:

  • 这个问题与从片段启动服务有关,因为当我从 FragmentActivity(主机 Activity)启动它时它可以工作。
  • 但是你的服务正在启动,它只是被杀死了。发生这种情况时,您的片段是否仍处于活动状态?我建议将 Log 标签放在一些生命周期方法中,以查看何时调用 onDestroy 与片段和活动生命周期的关系。我不知道为什么从上面发布的内容中调用了 onDestroy。
  • 我添加了AddNewRecordFragment,从我开始服务的地方开始。
  • 你在 case1 的结尾和 case2 的结尾打破怎么样。缺少中断的任何机会都会导致 case1 启动然后立即停止服务(因为那是 case2)
  • 就是这样!感谢您的帮助和耐心。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2013-03-06
相关资源
最近更新 更多