フラグメントからサービスを開始する際に問題があります。サービスは開始されていますが、フォアグラウンドではなく、isCancelled
変数が true に設定されている理由がわかりません (そのため、doInBackground
タスクは処理されません)。
a から開始すると、次のFragmentActivity
ように動作しますstartService(new Intent(this, Recorder.class));
。しかし、フラグメントから開始しようとすると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");
}
}