본문 바로가기

Android/Service with HttpClient

안드로이드 예제 Service with HttpClient

시스템 부팅시부터 주기적으로 백그라운드에서 실행되는 Service가 HttpClient를 사용하여 웹사이트의 정보를 확인하는 예제

AndroidManifest.xml

0: <?xml version="1.0" encoding="utf-8"?>
1: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2: package="test.android.hello"
3: android:versionCode="1"
4: android:versionName="1.0" >
5: <uses-sdk android:minSdkVersion="10" />
6: <uses-permission android:name="android.permission.INTERNET" />
7: <uses-permission android:name="android.permission.CALL_PHONE"/>
8: <uses-permission android:name="android.permission.SEND_SMS"/>
9: <uses-permission android:name="android.permission.CAMERA" />
10: <uses-feature android:name="android.hardware.camera" />
11: <uses-feature android:name="android.hardware.camera.autofocus" />
12: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
13: <uses-permission android:name="android.permission.RECORD_AUDIO"/>
14: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
15: <application
16: android:icon="@drawable/ic_launcher"
17: android:label="@string/app_name" >
18:  
19: <activity
20: android:name=".ServiceStarterActivity"
21: android:label="@string/app_name" >
22: <intent-filter>
23: <action android:name="android.intent.action.MAIN" />
24: <category android:name="android.intent.category.LAUNCHER" />
25: </intent-filter>
26: </activity>
27:  
28: <service android:name=".HttpRequestService" />
29: <receiver android:name=".BootBroadcastReceiver" android:label="@string/app_name">
30: <intent-filter>
31: <action android:name="android.intent.action.BOOT_COMPLETED" />
32: <category android:name="android.intent.category.LAUNCHER" />
33: </intent-filter>
34: </receiver>
35: </application>
36: </manifest>


BootBroadcastReceiver

 0:  package test.android.hello;
 1:  
 2:  import java.util.Calendar;
 3:  
 4:  import android.app.AlarmManager;
 5:  import android.app.PendingIntent;
 6:  import android.content.BroadcastReceiver;
 7:  import android.content.Context;
 8:  import android.content.Intent;
 9:  
10:  public class BootBroadcastReceiver extends BroadcastReceiver {
11:  
12:  	@Override
13:  	public void onReceive(Context context, Intent intent) {
14:  		 if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
15:  			 int SECS = 1000;
16:  			 int MINS = 60 * SECS;
17:  			 Calendar cal = Calendar.getInstance();
18:  			 Intent in = new Intent(context, HttpRequestService.class);
19:  			 PendingIntent pi = PendingIntent.getService(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
20:  			 AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
21:  			 alarms.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), MINS, pi);
22:  		}
23:  	}
24:  }


HttpRequestService

0: package test.android.hello; 1: 2: import java.io.DataInputStream; 3: import java.io.IOException; 4: import java.net.Socket; 5: 6: import android.app.Service; 7: import android.content.Intent; 8: import android.os.IBinder; 9: import android.util.Log; 10: 11: import android.app.Notification; 12: import android.app.NotificationManager; 13: import android.app.PendingIntent; 14: import android.content.BroadcastReceiver; 15: import android.content.Context; 16: import android.content.IntentFilter; 17: import android.net.Uri; 18: 19: public class HttpRequestService extends Service { 20: 21: private static final int MY_NOTIFICATION_ID=1; 22: private NotificationManager notificationManager; 23: private Notification myNotification; 24: private final String myBlog = "http://micropilot.tistory.com/"; 25: 26: @Override 27: public void onCreate() { 28: super.onCreate(); 29: } 30: 31: @Override 32: public int onStartCommand(Intent intent, int flags, int startId) { 33: 34: Log.i("서비스호출", "onStartCommand()실행됨"); 35: 36: HttpClientUtil httpUtil = new HttpClientUtil(); 37: String result = httpUtil.request("id", "pwd", 38: "http://xxxxxx.mireene.com/nms/isNewMsg.jsp"); //웹서버의 데이터 가져옴 39: if(result==null || !result.equals("1")) 40: super.onStartCommand(intent, flags, startId); 41: 42: // 웹서버에서 응답한 데이터가 "1"인 경우에만 이용자에게 Notification을 출력하여 알려 줌 43: notificationManager = 44: (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 45: myNotification = new Notification(R.drawable.ic_launcher, 46: "Notification!", 47: System.currentTimeMillis()); 48: Context context = getApplicationContext(); 49: String notificationTitle = "새로운 글 등록알림"; 50: String notificationText = "http://micropilot.tistory.com 접속"; 51: Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myBlog)); // 통지를 선택하면 웹사이트로 이동 52: PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 53: 0, myIntent, 54: Intent.FLAG_ACTIVITY_NEW_TASK); 55: myNotification.defaults |= Notification.DEFAULT_SOUND; 56: myNotification.flags |= Notification.FLAG_AUTO_CANCEL; 57: myNotification.setLatestEventInfo(context, 58: notificationTitle, 59: notificationText, 60: pendingIntent); 61: notificationManager.notify(MY_NOTIFICATION_ID, myNotification); 62: 63: return super.onStartCommand(intent, flags, startId); 64: } 65: 66: @Override 67: public void onDestroy() { 68: super.onDestroy(); 69: } 70: 71: @Override 72: public IBinder onBind(Intent arg0) { 73: return null; 74: } 75: }



HttpClientUtil

0: package test.android.hello; 1: 2: import java.io.*; 3: import java.util.*; 4: 5: import org.apache.http.*; 6: import org.apache.http.client.*; 7: import org.apache.http.client.entity.*; 8: import org.apache.http.client.methods.*; 9: import org.apache.http.impl.client.*; 10: import org.apache.http.message.*; 11: import org.apache.http.params.*; 12: 13: import android.util.Log; 14: 15: public class HttpClientUtil { 16: 17: public String request(String id, String pwd, String url){ 18: String result = null; 19: InputStream is = null; 20: String totalMessage = ""; 21: //String url = "http://xxxxxx.mireene.com/"; 22: HttpClient httpclient = new DefaultHttpClient(); 23: try { 24: /** 지정한 시간 내에 연결이 되지 않으면 오류를 발생하도록 설정함 */ 25: //String id = "id"; 26: //String pwd = "password"; 27: 28: ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(); 29: nameValuePairs.add(new BasicNameValuePair("ID", id)); 30: nameValuePairs.add(new BasicNameValuePair("PWD", pwd)); 31: 32: HttpParams params = httpclient.getParams(); 33: HttpConnectionParams.setConnectionTimeout(params, 5000); // 5초내에 연결되지 않으면 오류발생 34: HttpConnectionParams.setSoTimeout(params, 5000); 35: 36: HttpPost httppost = new HttpPost(url); 37: UrlEncodedFormEntity entityRequest = new UrlEncodedFormEntity(nameValuePairs, "UTF-8"); 38: httppost.setEntity(entityRequest); 39: 40: HttpResponse response = httpclient.execute(httppost); 41: HttpEntity entityResponse = response.getEntity(); 42: is = entityResponse.getContent(); 43: 44: /** convert response to string */ 45: BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); 46: 47: StringBuilder sb = new StringBuilder(); 48: String line = null; 49: while ((line = reader.readLine()) != null) { 50: sb.append(line).append("\n"); 51: } 52: is.close(); 53: result = sb.toString(); 54: 55: Log.i("응답결과", result); 56: } catch (IOException e) { 57: e.printStackTrace(); 58: }catch (Exception e){ 59: e.printStackTrace(); 60: } finally { 61: httpclient.getConnectionManager().shutdown(); 62: } 63: return result; 64: } 65: }



서버측 코드 (isNewMsg.jsp)

0: <%@ page language="java" contentType="text/plain; charset=EUC-KR" pageEncoding="EUC-KR"%>
1: <%="1"%><% out.flush(); %>