我在从片段启动服务时遇到问题。服务已启动,但它不是前台,我不知道为什么将isCancelled
变量设置为 true(因此doInBackground
未处理任务)。
当我从它开始时它FragmentActivity
可以工作:startService(new Intent(this, Recorder.class));
. 但是当我尝试从 Fragment 启动它时,getActivity().startService(new Intent(getActivity(), 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) {
}
}
}
添加新记录片段:
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");
}
}