25.03.2014, 20:52. Просмотров 853. Ответов 0
В Activity запускается сервис (работает в фоне), который обновляет ProgressBar, закрыв активность кнопкой Back и вернувшись снова, progressBar не обновляется, но сервис продолжает работать. Как можно подключиться к сервису и получить прогресс?
Пытаюсь сделать простой пример, пока выводящий просто значения в TextView. Но при закрытии активности и возврате в неё, данные в textView не обновляются.
MainActivity
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
| import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
final String LOG_TAG = "myLogs";
final int TASK1_CODE = 1;
final int TASK2_CODE = 2;
final int TASK3_CODE = 3;
public final static int STATUS_START = 100;
public final static int STATUS_FINISH = 200;
public final static String PARAM_TIME = "time";
public final static String PARAM_PINTENT = "pendingIntent";
public final static String PARAM_RESULT = "result";
TextView tvTask1;
TextView tvTask2;
TextView tvTask3;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTask1 = (TextView) findViewById(R.id.tvTask1);
tvTask1.setText("Task1");
tvTask2 = (TextView) findViewById(R.id.tvTask2);
tvTask2.setText("Task2");
tvTask3 = (TextView) findViewById(R.id.tvTask3);
tvTask3.setText("Task3");
}
public void onClickStart(View v) {
PendingIntent pi;
Intent intent;
// !!! NULL - В ВЕРСИИ ANDROID 4 НЕЛЬЗЯ ПРЕДАВАТЬ (НУЖНО СОЗДАТЬ ПУСТОЙ INTENT)
Intent emptyIntent = new Intent();
// Создаем PendingIntent для Task1
pi = createPendingResult(TASK1_CODE, emptyIntent, 0);
// Создаем Intent для вызова сервиса, кладем туда параметр времени
// и созданный PendingIntent
intent = new Intent(this, MyService.class).putExtra(PARAM_TIME, 7)
.putExtra(PARAM_PINTENT, pi);
// стартуем сервис
startService(intent);
pi = createPendingResult(TASK2_CODE, emptyIntent, 0);
intent = new Intent(this, MyService.class).putExtra(PARAM_TIME, 4)
.putExtra(PARAM_PINTENT, pi);
startService(intent);
pi = createPendingResult(TASK3_CODE, emptyIntent, 0);
intent = new Intent(this, MyService.class).putExtra(PARAM_TIME, 6)
.putExtra(PARAM_PINTENT, pi);
startService(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(LOG_TAG, "requestCode = " + requestCode + ", resultCode = "
+ resultCode);
// Ловим сообщения о старте задач
if (resultCode == STATUS_START) {
switch (requestCode) {
case TASK1_CODE:
tvTask1.setText("Task1 start");
break;
case TASK2_CODE:
tvTask2.setText("Task2 start");
break;
case TASK3_CODE:
tvTask3.setText("Task3 start");
break;
}
}
// Ловим сообщения об окончании задач
if (resultCode == STATUS_FINISH) {
int result = data.getIntExtra(PARAM_RESULT, 0);
switch (requestCode) {
case TASK1_CODE:
tvTask1.setText("Task1 finish, result = " + result);
break;
case TASK2_CODE:
tvTask2.setText("Task2 finish, result = " + result);
break;
case TASK3_CODE:
tvTask3.setText("Task3 finish, result = " + result);
break;
}
}
}
} |
|
MyService (В манифесте прописано <service android:name="MyService"></service>)
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
| import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.util.Log;
public class MyService extends Service {
final String LOG_TAG = "myLogs";
ExecutorService es;
public void onCreate() {
super.onCreate();
Log.d(LOG_TAG, "MyService onCreate");
es = Executors.newFixedThreadPool(2);
}
public void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "MyService onDestroy");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LOG_TAG, "MyService onStartCommand");
int time = intent.getIntExtra(MainActivity.PARAM_TIME, 1);
PendingIntent pi = intent.getParcelableExtra(MainActivity.PARAM_PINTENT);
MyRun mr = new MyRun(time, startId, pi);
es.execute(mr);
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent arg0) {
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(MainActivity.STATUS_START);
// начинаем выполнение задачи
TimeUnit.SECONDS.sleep(time);
// сообщаем об окончании задачи
Intent intent = new Intent().putExtra(MainActivity.PARAM_RESULT, time * 100);
pi.send(MyService.this, MainActivity.STATUS_FINISH, intent);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CanceledException e) {
e.printStackTrace();
}
stop();
}
void stop() {
Log.d(LOG_TAG, "MyRun#" + startId + " end, stopSelfResult("
+ startId + ") = " + stopSelfResult(startId));
}
}
} |
|
0
|