我有一项活动可以开始我的服务。启动后,服务应该在片段中发送数据。在宽阔的沟渠上显示服务已经启动,已经开始运营,但是片段没有发出广泛的沟渠,表明它已经获得了数据。我怎样才能进行这样的连锁活动 - >服务 - >一个片段?
main.java(活动)
kill = new Intent(this, timer.class);
pi = createPendingResult(TASK1_CODE, kill, 0);
intent = new Intent(this, timer.class).putExtra(PARAM_TIME, 7)
.putExtra(PARAM_PINTENT, pi);
startService(intent);
pi = createPendingResult(TASK2_CODE, kill, 0);
intent = new Intent(this, timer.class).putExtra(PARAM_TIME, 4)
.putExtra(PARAM_PINTENT, pi);
startService(intent);
pi = createPendingResult(TASK3_CODE, kill, 0);
intent = new Intent(this, timer.class).putExtra(PARAM_TIME, 6)
.putExtra(PARAM_PINTENT, pi);
startService(intent);
timer.java(服务)
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "MyService onStartCommand");
int time = intent.getIntExtra(user_rassp.PARAM_TIME, 1);
PendingIntent pi = intent.getParcelableExtra(user_rassp.PARAM_PINTENT);
MyRun mr = new MyRun(time, startId, pi);
es.execute(mr);
return START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
class MyRun implements Runnable {
int time;
int startId;
PendingIntent pi;
public MyRun(int time, int startId, PendingIntent pi) {
this.time = time;
this.startId = startId;
this.pi = pi;
Log.d(LOG_TAG, "MyRun#" + startId + " create");
}
public void run() {
Log.d(LOG_TAG, "MyRun#" + startId + " start, time = " + time);
try {
pi.send(user_rassp.STATUS_START);
TimeUnit.SECONDS.sleep(time);
Intent intent = new Intent().putExtra(user_rassp.PARAM_RESULT, time * 100);
Log.d(LOG_TAG, "конец");
pi.send(timer.this, user_rassp.STATUS_FINISH, intent);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
stop();
}
void stop() {
Log.d(LOG_TAG, "MyRun#" + startId + " end, stopSelfResult("
+ startId + ") = " + stopSelfResult(startId));
}
}
user_rasp.java(片段)
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(LOG_TAG, "requestCode = " + requestCode + ", resultCode = "
+ resultCode);
// Ловим сообщения о старте задач
if (resultCode == STATUS_START) {
switch (requestCode) {
case TASK1_CODE:
Log.d("task1","start");
break;
case TASK2_CODE:
Log.d("task1", "start");
break;
case TASK3_CODE:
Log.d("task1", "start");
break;
}
}
// Ловим сообщения об окончании задач
if (resultCode == STATUS_FINISH) {
int result = data.getIntExtra(PARAM_RESULT, 0);
switch (requestCode) {
case TASK1_CODE:
Log.d("Task1", "finish, result = " + result);
break;
case TASK2_CODE:
Log.d("Task2", "finish, result = " + result);
break;
case TASK3_CODE:
Log.d("Task3", "finish, result = " + result);
break;
}
}
}
答案 0 :(得分:0)
在Fragment中注册BroadCastReceiver。你需要为它使用一个动作。
来自Service发送带有上述Intent Action的broadcastMessage。您可以通过Intent extras传递数据