Background Servic zum Bilder laden

  • Antworten:2
mybecks
  • Forum-Beiträge: 27

01.10.2010, 14:30:47 via Website

Hallo zusammen,

Meine Idee ist es, ein Bild von einem Speicherplatz im Web (URL) alle 5 sec. herunterzuladen und in meiner Activity darstellen.
So nun habe ich mir gedacht, dass das ganze ja irgendwie im Hintergrund laufen muss, also habe ich einen Service erstellt.
Dieser Service wird durch ein Button auf dem UI gestartet und beendet.

So aber wie kann ich nun meine ImageView alle z.B. 5sec. "updaten". Ich habe ja im Service keinen zugriff auf die Activity.

Service:
1public class ImageService extends Service {
2
3 private final String TAG = "";
4 private final String URL = "http://www.mind-the-app.de/wp-content/uploads/2010/02/android.gif";
5 private final Handler handler = new Handler();
6 private final Timer timer = new Timer();
7
8 @Override
9 public IBinder onBind(Intent arg0) {
10
11 return null;
12 }
13
14 @Override
15 public void onCreate() {
16 super.onCreate();
17 Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
18 Log.i("Service", "onCreate");
19 }
20
21 @Override
22 public void onDestroy() {
23 super.onDestroy();
24 Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
25 Log.i("Service", "onDestroy");
26 timer.cancel();
27 }
28
29 @Override
30 public void onStart(Intent intent, int startid) {
31 Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
32
33
34 Log.i("Service", "onStart");
35
36 timer.scheduleAtFixedRate(update, 0, 500);
37// task being the method to be executed
38// after the time to initial execution
39// (interval the time for repeating the execution)
40 }
41
42 final TimerTask update = new TimerTask() {
43
44 @Override
45 public void run() {
46
47 currentImage();
48 }
49 };
50
51 public Drawable currentImage(){
52//Image updaten
53//...
54//...
55 return loadImageFromWeb(URL);
56 }
57
58 private Drawable loadImageFromWeb(String url) {
59 Log.i("", "Loading Image.");
60 try {
61 InputStream is = (InputStream) new URL(url).getContent();
62 Drawable d = Drawable.createFromStream(is, "src name");
63 return d;
64 } catch (Exception e) {
65 System.out.println("Exc=" + e);
66 return null;
67 }
68 }
69
70 @Override
71 public void onLowMemory() {
72 super.onLowMemory();
73 onDestroy();
74 }


Activity:
1btn_start.setOnClickListener(new OnClickListener() {
2
3 @Override
4 public void onClick(View v) {
5 startService(new Intent(LiveView.this, ImageService.class));
6 }
7 });
8
9 btn_stop.setOnClickListener(new OnClickListener() {
10
11 @Override
12 public void onClick(View v) {
13 stopService(new Intent(LiveView.this, ImageService.class));
14 }
15 });


Viele Grüße,
mybecks

— geändert am 01.10.2010, 15:19:21

Antworten
mybecks
  • Forum-Beiträge: 27

01.10.2010, 21:43:53 via Website

Vielen Dank.

Ich schaus mir an.

Viele Grüße,
mybecks

Antworten