개발도구/aOS - 안드로이드 개발
[안드로이드] Push 1 강의 - 2.1 이하 (2.2이상도 됨)
Hay's App
2011. 9. 7. 15:40
한 일주일간 고생 끝네 해결했습니다.
먼저 회사에 2.1 방식을 채택하여 사용중이었습니다.
어플 <-> 회사서버
시간을 두어 전송하고 받는거였지요...
하지만, 이렇게 하면 간단하게 처리할수도 있지만,
고객이 많아지고 푸시량이 많아 질때, 또한 핸드폰에선 어플 <-> 회사서버 에 계속 연결을 하고 있어야 하기에 핸폰 배터리도 많이 달게 되죠..
안드로이드 폰 -> 설정 -> 응용프로그램 -> 실행중인 응용프로그램
에서 보시면 날씨 및 여러 어플, 뉴스 어플중에 관해서 alarm(푸시) 을 기다리고 있습니다.
이 방식은 모라 하지요?? 글쎄요.. 2.1(sdk 7) 버전까지 사용되었다가 sdk 8(2.2) 부터 는 C2DM 방식을 채택할수 있답니다.
그럼 당연히 sdk 7 에서는 C2DM 이 안되겠죠!! 그러나 2.1 방식은 2.2 에서도 실행이 됩니다. 그러나 이렇게 사용하면 과부화. ㅠㅠ
소스 전부를 올려드리고 싶지만, 보안상
간단히 흐름을 올려 드리자면요..
sdk 7 - 2.1(물론 2.2 이상도 됩니다.)
index.class
먼저 회사에 2.1 방식을 채택하여 사용중이었습니다.
어플 <-> 회사서버
시간을 두어 전송하고 받는거였지요...
하지만, 이렇게 하면 간단하게 처리할수도 있지만,
고객이 많아지고 푸시량이 많아 질때, 또한 핸드폰에선 어플 <-> 회사서버 에 계속 연결을 하고 있어야 하기에 핸폰 배터리도 많이 달게 되죠..
안드로이드 폰 -> 설정 -> 응용프로그램 -> 실행중인 응용프로그램
에서 보시면 날씨 및 여러 어플, 뉴스 어플중에 관해서 alarm(푸시) 을 기다리고 있습니다.
이 방식은 모라 하지요?? 글쎄요.. 2.1(sdk 7) 버전까지 사용되었다가 sdk 8(2.2) 부터 는 C2DM 방식을 채택할수 있답니다.
그럼 당연히 sdk 7 에서는 C2DM 이 안되겠죠!! 그러나 2.1 방식은 2.2 에서도 실행이 됩니다. 그러나 이렇게 사용하면 과부화. ㅠㅠ
소스 전부를 올려드리고 싶지만, 보안상
간단히 흐름을 올려 드리자면요..
sdk 7 - 2.1(물론 2.2 이상도 됩니다.)
index.class
PendingIntent mAlarmSender = PendingIntent.getService(this,
0, new Intent(this, NewsAlarmService.class), 0);
AlarmManager am = (AlarmManager)this.getSystemService(android.content.Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
Integer.parseInt(this.getText(R.string.pushTime).toString()), mAlarmSender);
NewsAlarmService .class
public class NewsAlarmService extends Service{
NotificationManager mNM;
private int ID =1;
private Timer timer;
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
try {
showNotification();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Log.e("test", "Error notice "+e.toString());
}
//Log.e("test", "ttttttt ");
// timer = new Timer();
//timer.schedule(myTask, 5000, 10*1000);
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block.
Thread thr = new Thread(null, mTask, "mNewsAlarmService_Service");
thr.start();
}
TimerTask myTask = new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
showNotification();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
@Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
//mNM.cancel(R.string.alarm_service_started);
// Tell the user we stopped.
//Toast.makeText(this, "alram finish", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
//Log.i("test", getText(R.string.pushTime).toString());
// Normally we would do some work here... for our sample, we will
// just sleep for 30 seconds.
long endTime = System.currentTimeMillis() + Integer.parseInt(getText(R.string.pushTime).toString())-10*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (mBinder) {
try {
mBinder.wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Done with our work... stop the service!
NewsAlarmService.this.stopSelf();
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
* @throws UnsupportedEncodingException
*/
private void showNotification() throws UnsupportedEncodingException {
SharedPreferences common =
getSharedPreferences("COMMON_MONEYTODAYNEWS",MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE);
if(common.getBoolean("getStock", false) || common.getBoolean("getNews", false)){
}else{
// Log.e("test", "ssssss ");
return;
}
String result = "";
//the year data to send
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// Log.e("test", tm.getDeviceId());
//the year data to send
ArrayList nameValuePairs = new ArrayList();
//nameValuePairs.add(new BasicNameValuePair("userId",URLEncoder.encode(common.getString("UID", ""))));
nameValuePairs.add(new BasicNameValuePair("deviceToken",tm.getDeviceId()));
if(android.os.Build.VERSION.SDK_INT <= 7){
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
// getMyPush.html - 원래 사용중인 파일이름!!!
//HttpPost httppost = new HttpPost(getText(R.string.domain).toString()+"/pushService/getMyPush.html");
HttpPost httppost = new HttpPost("http://....../pushService/getMyPush2.html");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"euc-kr"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("test", "Error converting result "+e.toString());
}
}
String msg ="";
String article_id = "";
String category = "";
//parse json data
try{
JSONArray jArray = new JSONArray(result);
Notification notification = null;
for(int i=0;i 20 ) {
msg = msg.substring(0,20) + "..";
}
CharSequence text = msg;
// Set the icon, scrolling text and timestamp
notification = new Notification(R.drawable.mt_iconbig, text,
System.currentTimeMillis());
notification.flags |= notification.FLAG_AUTO_CANCEL;
notification.flags |= notification.DEFAULT_SOUND;
notification.flags |= notification.DEFAULT_VIBRATE;
// notification.number = 3;
// Intent i = new Intent(this, RepeatingAlarm.class);
//Uri appWidgetUri = Uri.parse("teststst");
// i.setData(appWidgetUri);
//i.putExtra("AlarmID", articel_id);
// The PendingIntent to launch our activity if the user selects this notification
// PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0,
// i,PendingIntent.FLAG_UPDATE_CURRENT);
// Set the info for the views that show in the notification panel.
// notification.setLatestEventInfo(this, getText(R.string.alarm_service_label),
// text, contentIntent);
notification.setLatestEventInfo(this, text,
"", makeControlPendingIntent(this,article_id));
notification.vibrate = new long[] { 100, 250, 100, 500};
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(7671, notification);
//mNM.notify(Integer.parseInt(article_id.substring(10,17)), notification);
// Log.i("test", "article_id"+article_id.substring(10,17));
// Thread.sleep(500);
}
}
}catch(JSONException e){
//Log.e("test", "Error parsing data "+e.toString());
}
//Log.e("test", "Error loading");
// In this sample, we'll use the same text for the ticker and the expanded notification
}
private PendingIntent makeControlPendingIntent(Context context, String command) {
Intent active = new Intent(context,RepeatingAlarm.class);
active.setAction("ACTION_VIEW");
Uri data = Uri.parse(command);
// Uri data = Uri.withAppendedPath(
// Uri.parse(command),appWidgetId);
active.setData(data);
return(PendingIntent.getBroadcast(context,
0, active, 0));
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
RepeatingAlarm.class
public class RepeatingAlarm extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
//Toast.makeText(context, "connect ", Toast.LENGTH_SHORT).show();
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
// Log.d("test","We got here!");
}else{
//Toast.makeText(context, intent.getData().toString(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MenuMt.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("num", intent.getData().toString());
i.putExtra("type", "alarm");
context.startActivity(i);
}
}
}