본문 바로가기

Android/Notification Service

안드로이드 Notification Service 예제

안드로이드 Service가 제목 표시줄에 통지(Notification)를 표시하고 이용자가 통지를 열고 선택하면 웹브라우저가  웹사이트에 접속하는 예

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="test.android.hello" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.CALL_PHONE"/> <uses-permission android:name="android.permission.SEND_SMS"/> <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.RECORD_AUDIO"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".ServiceStarterActivity" 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=".MyNotifyService" /> </application> </manifest>


main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onBtnStart" android:text="Service 실행 및 Notification 표시" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onBtnStop" android:text="Service 종료" /> </LinearLayout>


ServiceStarterActivity

package test.android.hello; import test.android.hello.MyNotifyService.NotifyServiceReceiver; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class ServiceStarterActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onBtnStart(View v) { Intent intent = new Intent(this, MyNotifyService.class); startService(intent); } public void onBtnStop(View v) { Intent intent = new Intent(); intent.setAction(MyNotifyService.ACTION); intent.putExtra("RQS", MyNotifyService.RQS_STOP_SERVICE); sendBroadcast(intent); } }


MyNotifyService (BroadcastReceiver 포함)

package test.android.hello; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.IBinder; public class MyNotifyService extends Service { final static String ACTION = "NotifyServiceAction"; final static String STOP_SERVICE = ""; final static int RQS_STOP_SERVICE = 1; // 내부클래스로 선언된 BroadcastReceiver NotifyServiceReceiver notifyServiceReceiver; private static final int MY_NOTIFICATION_ID=1; private NotificationManager notificationManager; private Notification myNotification; private final String myBlog = "http://micropilot.tistory.com/"; @Override public void onCreate() {

// 현재 애플리케이션에서만 사용할 BroadcastReceiver 인스턴스 생성 notifyServiceReceiver = new NotifyServiceReceiver(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ACTION); // 애플리케이션의 메인 쓰레드 안에서 실행되는 BroadcastReceiver 등록 registerReceiver(notifyServiceReceiver, intentFilter); // Send Notification notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); myNotification = new Notification(R.drawable.ic_launcher, "Notification!", System.currentTimeMillis()); Context context = getApplicationContext(); String notificationTitle = "새로운 글 등록알림"; String notificationText = "http://micropilot.tistory.com 접속";

// 이용자가 Notification을 선택하면 웹브라우저를 실행하기위한 설정 Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog)); PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK); myNotification.defaults |= Notification.DEFAULT_SOUND; myNotification.flags |= Notification.FLAG_AUTO_CANCEL; myNotification.setLatestEventInfo(context, notificationTitle, notificationText, pendingIntent); notificationManager.notify(MY_NOTIFICATION_ID, myNotification); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { this.unregisterReceiver(notifyServiceReceiver); super.onDestroy(); } @Override public IBinder onBind(Intent arg0) { return null; } /* 내부 클래스로 정의한 BroadcastReceiver */ public class NotifyServiceReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { int rqs = arg1.getIntExtra("RQS", 0); if (rqs == RQS_STOP_SERVICE){ // Service 클래스의 멤버 메소드 stopSelf()는 stopService()와 동일한 기능을 한다 stopSelf(); } } }// 내부 클래스 끝 }