본문 바로가기

Android

[Thread/Service/Broadcast] 5초마다 Toast 띄우기

 시나리오는 다음과 같다:


1. Thread가 5초마다 sleep 한다.

2. Service는 Thread가 sleep 했다는 신호를 보낸다.

3. Broadcast Receiver가 그 신호를 받아서Toast로 유저에게 알려준다.





 결과화면: 5초마다 Toast 메세지가 뜬다.





 이 예제로 깨달은 것

1. 자바 작명법을 꼭 따르자.

클래스 이름을 "Service"로 했더니 에러나 경고는 안뜨지만 

내부적인 문제점으로 인해 제대로 작동하지 않았다.

"android.app.Service"와 맞물렸던 것이다.

context.startService(new Intent(MainActivity.this, Service.class));


2. sendBroadcast() 할 때에는 Intent에 퍼미션을 꼭 달아주어야 한다.

그렇지 않으면 Receiver가 신호를 받을 수 없다.

Intent i = new Intent("Nay"); //send 부분

filter.addAction("Nay"); //receiver 부분


3. Log 메서드를 적극 활용하자.

어디까지 실행되고 어느 부분이 작동안하는지 알 수 있다.

구글링, stack overflow에 질문을 해도 문제 해결이 안되었는데..

Logcat을 보고 차근차근히 혼자 힘으로 해결할 수 있었다.

시간은 좀 많이 잡아먹었지만...


4. Service를 외부에서 호출하면 진짜 onStartcommand()로 간다.

우왕 로그캣으로 보면서도 안믿김 ㅋㅋㅋㅋ



 소스코드


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
 
package com.bignerdranch.android.thsebr;
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
 
 
public class MainActivity extends ActionBarActivity implements Runnable {
    Thread mThread;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Log.d("Activity""onCreate()");
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Activity""onStart()");
 
        mThread = new Thread(this);
        mThread.start();
    }
 
    @Override
    public void run() {
        Log.d("Thread""run()");
 
        while(true) {
            try {
                mThread.sleep(5000);
            } catch (InterruptedException e) {
                //empty
            }
            Log.d("Thread""sleep");
 
            Context context = getApplicationContext();
            context.startService(new Intent(MainActivity.this, MyService.class));
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Activity""onResume()");
 
        IntentFilter filter = new IntentFilter();
        filter.addAction("Nay");
        registerReceiver(mBroadcastReceiver, filter);
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Activity""onPause()");
 
        unregisterReceiver(mBroadcastReceiver);
    }
 
    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
 
            if (action.equals("Nay")) {
                Log.i("onReceive()", action);
                Toast.makeText(MainActivity.this"sleep sleep sleep", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
 
cs



MyService.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
 
package com.bignerdranch.android.thsebr;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
 
/**
 * Created by NAYEON on 2015-07-02.
 */
public class MyService extends Service {
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService""onStartCommand");
 
        Intent i = new Intent("Nay");
        intent.putExtra("number"7);
        sendBroadcast(i);
        Log.i("MyService""send");
 
        return START_NOT_STICKY;
    }
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
 
cs



Manifest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bignerdranch.android.thsebr" >
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"
                 android:enabled="true" />
    </application>
</manifest>
 
cs