시나리오는 다음과 같다: |
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.d("Activity", "onCreate()");}@Overrideprotected void onStart() {super.onStart();Log.d("Activity", "onStart()");mThread = new Thread(this);mThread.start();}@Overridepublic 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));}}@Overrideprotected void onResume() {super.onResume();Log.d("Activity", "onResume()");IntentFilter filter = new IntentFilter();filter.addAction("Nay");registerReceiver(mBroadcastReceiver, filter);}@Overrideprotected void onPause() {super.onPause();Log.d("Activity", "onPause()");unregisterReceiver(mBroadcastReceiver);}BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {@Overridepublic 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
12345678910111213141516171819202122232425262728293031 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 {@Overridepublic 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;}@Overridepublic IBinder onBind(Intent intent) {return null;}}cs Manifest.xml
1234567891011121314151617181920212223 <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.bignerdranch.android.thsebr" ><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid: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
'Android' 카테고리의 다른 글
[Why] 영구적인 data를 저장할 때, onPause()가 안전하다. (0) | 2015.07.27 |
---|---|
Windows에서 git이랑 연결하기 (0) | 2015.07.13 |
Fragment를 호스팅하는 Activity (0) | 2015.06.30 |
setRetainInstance(true) Vs onSaveInstanceState(Bundle) (0) | 2015.06.23 |
Android Studio에서 @drawable 대신 @mipmap! (0) | 2015.06.23 |