/** * A broadcast receiver to handle the changes in network connectiion states. * * <p><<<<<<< HEAD * * @author Sehwan Noh ([email protected]) 192.168.0 * <p>======= * @author Sehwan Noh ([email protected]) >>>>>>> origin/master */ public class ConnectivityReceiver extends BroadcastReceiver { private static final String LOGTAG = LogUtil.makeLogTag(ConnectivityReceiver.class); private ConnectService connectionService; public ConnectivityReceiver(ConnectService connectionService) { this.connectionService = connectionService; } @Override public void onReceive(Context context, Intent intent) { Log.d(LOGTAG, "ConnectivityReceiver.onReceive()..."); String action = intent.getAction(); Log.d(LOGTAG, "action=" + action); ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (networkInfo != null) { Log.d(LOGTAG, "Network Type = " + networkInfo.getTypeName()); Log.d(LOGTAG, "Network State = " + networkInfo.getState()); if (networkInfo.isConnected()) { Log.i(LOGTAG, "Network connected"); connectionService.connect(); } } else { Log.e(LOGTAG, "Network unavailable"); connectionService.disconnect(); } } }
public class NotificationPacketListener implements PacketListener { private static final String LOGTAG = LogUtil.makeLogTag(NotificationPacketListener.class); private final XmppManager xmppManager; public NotificationPacketListener(XmppManager xmppManager) { this.xmppManager = xmppManager; } public void processPacket(Packet packet) { Log.d(LOGTAG, "NotificationPacketListener.processPacket()..."); Log.d(LOGTAG, "packet.toXML()=" + packet.toXML()); if (packet instanceof NotificationIQ) { NotificationIQ notification = (NotificationIQ) packet; if (notification.getChildElementXML().contains("androidpn:iq:notification")) { Log.d(LOGTAG, "ChildElementXML=" + notification.getChildElementXML()); String configID = notification.getConfigID(); String devID = notification.getDeviceID(); ArrayList<Resource> lists = notification.getResources(); String notificationFrom = notification.getFrom(); String packetId = notification.getPacketID(); Intent intent = new Intent(Constants.ACTION_SHOW_NOTIFICATION); intent.putExtra(Constants.NOTIFICATION_CONFIGURATION, configID); intent.putExtra(Constants.NOTIFICATION_DEVICEID, devID); /*将resource list 放入bundle中,将bundle放入Intent中,进行传输*/ Bundle bundle = new Bundle(); bundle.putParcelableArrayList(Constants.NOTIFICATION_RESOURCES_LIST, lists); Log.d("NPListener", "put the lists to the bundle then to the intent~~"); intent.putExtras(bundle); intent.putExtra(Constants.NOTIFICATION_FROM, notificationFrom); intent.putExtra(Constants.PACKET_ID, packetId); IQ result = NotificationIQ.createResultIQ(notification); xmppManager.getConnection().sendPacket(result); xmppManager.getContext().sendBroadcast(intent); } } } }
/** * Broadcast receiver that handles push notification messages from the server. This should be * registered as receiver in AndroidManifest.xml. * * @author Sehwan Noh ([email protected]) */ public final class NotificationReceiver extends BroadcastReceiver { private static final String LOGTAG = LogUtil.makeLogTag(NotificationReceiver.class); // private NotificationService notificationService; public NotificationReceiver() {} // public NotificationReceiver(NotificationService notificationService) { // this.notificationService = notificationService; // } @Override public void onReceive(Context context, Intent intent) { Log.d(LOGTAG, "NotificationReceiver.onReceive()..."); String action = intent.getAction(); Log.d(LOGTAG, "action=" + action); if (Constants.ACTION_SHOW_NOTIFICATION.equals(action)) { String notificationId = intent.getStringExtra(Constants.NOTIFICATION_ID); String notificationApiKey = intent.getStringExtra(Constants.NOTIFICATION_API_KEY); String notificationTitle = intent.getStringExtra(Constants.NOTIFICATION_TITLE); String notificationMessage = intent.getStringExtra(Constants.NOTIFICATION_MESSAGE); String notificationUri = intent.getStringExtra(Constants.NOTIFICATION_URI); String notificationFrom = intent.getStringExtra(Constants.NOTIFICATION_FROM); String packetId = intent.getStringExtra(Constants.PACKET_ID); Log.d(LOGTAG, "notificationId=" + notificationId); Log.d(LOGTAG, "notificationApiKey=" + notificationApiKey); Log.d(LOGTAG, "notificationTitle=" + notificationTitle); Log.d(LOGTAG, "notificationMessage=" + notificationMessage); Log.d(LOGTAG, "notificationUri=" + notificationUri); Notifier notifier = new Notifier(context); notifier.notify( notificationId, notificationApiKey, notificationTitle, notificationMessage, notificationUri, notificationFrom, packetId); } } }
/** * Broadcast receiver that handles push notification messages from the server. This should be * registered as receiver in AndroidManifest.xml. * * @author winters_huang */ public final class BootDemoReceiver extends BroadcastReceiver { private static final String LOGTAG = LogUtil.makeLogTag(BootDemoReceiver.class); private ServiceManager serviceManager; public BootDemoReceiver() {} @Override public void onReceive(Context context, Intent intent) { Log.d(LOGTAG, "BootReceiverr.onReceive()..."); String action = intent.getAction(); Log.d(LOGTAG, "action=" + action); // 启动推送服务 serviceManager = new ServiceManager(context); serviceManager.startService(); } }
/** * A listener class for monitoring connection closing and reconnection events. * * @author Sehwan Noh ([email protected]) */ public class PersistentConnectionListener implements ConnectionListener { private static final String LOGTAG = LogUtil.makeLogTag(PersistentConnectionListener.class); private final XmppManager xmppManager; public PersistentConnectionListener(XmppManager xmppManager) { this.xmppManager = xmppManager; } @Override public void connectionClosed() { Log.d(LOGTAG, "connectionClosed()..."); } @Override public void connectionClosedOnError(Exception e) { Log.d(LOGTAG, "connectionClosedOnError()..."); if (xmppManager.getConnection() != null && xmppManager.getConnection().isConnected()) { xmppManager.getConnection().disconnect(); } // xmppManager.startReconnectionThread(); } @Override public void reconnectingIn(int seconds) { Log.d(LOGTAG, "reconnectingIn()..."); } @Override public void reconnectionFailed(Exception e) { Log.d(LOGTAG, "reconnectionFailed()..."); } @Override public void reconnectionSuccessful() { Log.d(LOGTAG, "reconnectionSuccessful()..."); } }
public class MsgUtil { private static final String TAG = LogUtil.makeLogTag(MsgUtil.class); // {"type":"系统消息","sid":"1","title":"版本更新","pubtime":"2012-09-19 // 10:53:19","typeid":1,"iswav":0,"isshock":0,"msgid":1,"summary":"有新版本更新"} public static NotificationVo getStringToObj(String jArr, NotificationVo nv) { NotificationVo result = nv; try { LogUtil.d(TAG, "json :---------" + jArr.toString()); JSONObject objJson = new JSONObject(jArr); String msgType = objJson.getString("msg_type"); String msgId = objJson.getString("msgId"); String msgClassName = objJson.getString("msgClassName"); String msgFromClassName = objJson.getString("mfcName"); boolean isPing = objJson.getBoolean("isPing"); boolean isShock = objJson.getBoolean("isShock"); String msgc = objJson.getString("msg_c"); if ("2".equals(msgType)) { String msgToType = objJson.getString("msgToType"); String strData = objJson.getString("strData"); result.setStrData(strData); result.setMsgToType(msgToType); } else { String openUrl = objJson.getString("open_url"); nv.setOpenUrl(openUrl); } result.setMsgId(msgId); result.setMsgClassName(msgClassName); result.setMsgFromClassName(msgFromClassName); result.setMsgType(msgType); result.setPing(isPing); result.setShock(isShock); result.setMsgC(msgc); } catch (Exception e) { e.printStackTrace(); } return result; } public static MsgVo getStringToObj(String jArr) { MsgVo result = new MsgVo(); try { LogUtil.d(TAG, "json :---------" + jArr.toString()); JSONObject objJson = new JSONObject(jArr); String msgid = objJson.getString("msgid"); String summary = objJson.getString("summary"); String title = objJson.getString("title"); String iswav = objJson.getString("iswav"); String isshock = objJson.getString("isshock"); String pubtime = objJson.getString("pubtime"); result.setIsshock(isshock); result.setIswav(iswav); result.setPubtime(pubtime); result.setMsgid(msgid); result.setSummary(summary); result.setTitle(title); } catch (Exception e) { e.printStackTrace(); } return result; } public static Map<String, Object> getStringPlace(String json) { Map<String, Object> res = new HashMap<String, Object>(); try { SubjectVo mSV = new SubjectVo(); JSONObject objItem = new JSONObject(json); String subjectname = objItem.getString("subjectname"); String subjectid = objItem.getString("subjectid"); mSV.setSubjectId(subjectid); mSV.setSubjectName(subjectname); res.put("sv", mSV); String[] id = null; String[] name = null; JSONArray classList = objItem.getJSONArray("classlist"); if (classList != null && classList.length() > 0) { id = new String[classList.length()]; name = new String[classList.length()]; for (int i = 0; i < classList.length(); i++) { JSONObject classItem = (JSONObject) classList.get(i); String classid = classItem.getString("classid"); String schoollocation = classItem.getString("schoollocation"); name[i] = schoollocation; id[i] = classid; LogUtil.d("&&&&&&&", schoollocation + " classid : " + classid); } res.put("name", name); res.put("id", id); } } catch (Exception e) { e.printStackTrace(); } return res; } public static TeacherVo getTeacher(String json) { TeacherVo result = new TeacherVo(); try { JSONObject teacherItem = new JSONObject(json); String teacherid = teacherItem.getString("teacherid"); String cnname = teacherItem.getString("cnname"); String country = teacherItem.getString("country"); String birthday = teacherItem.getString("birthday"); String enname = teacherItem.getString("enname"); String info = teacherItem.getString("info"); String sex = teacherItem.getString("sex"); String picture = teacherItem.getString("imgurl"); String zhicheng = teacherItem.getString("zhicheng"); String jingyan = teacherItem.getString("jingyan"); String techclass = teacherItem.getString("techclass"); int star = teacherItem.getInt("star"); int isarchived = teacherItem.getInt("isarchived"); result.setIsarchived(isarchived); result.setStar(star); result.setTeacherid(teacherid); result.setCnname(cnname); result.setBirthday(birthday); result.setCountry(country); result.setEnname(enname); result.setInfo(info); result.setPicture(picture); result.setSex(sex); result.setJingyan(jingyan); result.setZhicheng(zhicheng); result.setTechclass(techclass); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return result; } }
/** * Activity 显示通知信息界面. * * @author Sehwan Noh ([email protected]) */ public class NotificationDetailsActivity extends Activity { private Context context; String notificationId; String notificationApiKey; String notificationTitle; String notificationMessage; String notificationUri; String notificationFrom; String packetId; String bodyHtml; String htmlPost = "</body></html>"; String htmlPre = "<!DOCTYPE html>" + "<html lang=\"en\">" + "<head><meta charset=\"utf-8\">" + "</head>" + "<body style='margin:0; pading:0;" + " background-color: #71D5CA;'>"; private static final String LOGTAG = LogUtil.makeLogTag(NotificationDetailsActivity.class); private String callbackActivityPackageName; private String callbackActivityClassName; private String rtmpUrl; private String fileName; private int msgStart, msgEnd; private int mobileWidthPix, mobileHeightPix, mobileWidth, mobileHeight, densityDPI; float density; private LinearLayout.LayoutParams contentParams, videoParams, titleParams, buttonParams, responseParams; private ScrollView scrollView; private LinearLayout responseLayout; private boolean flag = false; private SharedPreferences originSharedPrefs; public NotificationDetailsActivity() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); originSharedPrefs = this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // 屏幕宽 mobileWidthPix = dm.widthPixels; // 屏幕高 mobileHeightPix = dm.heightPixels; density = dm.density; // 屏幕密度(0.75/1.0/1.5) Log.i("xiaobingo", "density是:" + density); // densityDPI = dm.densityDpi; //屏幕密度DPI (120/160/240) mobileWidth = (int) (mobileWidthPix / density + 0.5f); mobileHeight = (int) (mobileHeightPix / density + 0.5f); Log.i("xiaobingo", "屏幕宽:" + mobileWidth); Log.i("xiaobingo", "屏幕高:" + mobileHeight); SharedPreferences sharedPrefs = this.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); callbackActivityPackageName = sharedPrefs.getString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, ""); callbackActivityClassName = sharedPrefs.getString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, ""); Log.i(LOGTAG, "callbackActivity是:" + callbackActivityClassName); context = Constants.xmppManager.getContext(); Intent intent = getIntent(); if (intent.getStringExtra("ItemTitle") != null) { // 来自主页面DemoAppActivity点击单项的intent,不是通知页面Notifier转过来的intent Bundle bundle = this.getIntent().getExtras(); notificationTitle = bundle.getString("ItemTitle"); notificationMessage = bundle.getString("ItemMessage"); notificationUri = bundle.getString("ItemUri"); } else { // 来自通知页面Notifier传来的intent,需要增加userInfo内容 notificationId = intent.getStringExtra(Constants.NOTIFICATION_ID); notificationApiKey = intent.getStringExtra(Constants.NOTIFICATION_API_KEY); notificationTitle = intent.getStringExtra(Constants.NOTIFICATION_TITLE); notificationMessage = intent.getStringExtra(Constants.NOTIFICATION_MESSAGE); notificationUri = intent.getStringExtra(Constants.NOTIFICATION_URI); notificationFrom = intent.getStringExtra(Constants.NOTIFICATION_FROM); packetId = intent.getStringExtra(Constants.PACKET_ID); Log.d(LOGTAG, "notificationId=" + notificationId); Log.d(LOGTAG, "notificationApiKey=" + notificationApiKey); Log.d(LOGTAG, "notificationTitle=" + notificationTitle); Log.d(LOGTAG, "notificationMessage=" + notificationMessage); Log.d(LOGTAG, "notificationUri=" + notificationUri); Log.d(LOGTAG, "notificationFrom=" + notificationFrom); // TODO FIXME 发送查看回执 IQ result = new IQ() { @Override public String getChildElementXML() { return null; } }; result.setType(Type.RESULT); result.setPacketID(packetId); result.setTo(notificationFrom); try { Constants.xmppManager.getConnection().sendPacket(result); } catch (Exception e) { } // 保存通知标题和信息到userInfo中,以便保存在DemoAppActivity的浏览历史记录里 UserInfo userInfo = (UserInfo) context.getApplicationContext(); // userInfo.setMyNotifierTitle(title); // userInfo.setMyNotifierMessage(message); // userInfo.setMyNotifierUri(uri); HashMap<String, String> addMap = new HashMap<String, String>(); addMap.put("ItemTitle", notificationTitle); addMap.put("ItemMessage", notificationMessage); addMap.put("ItemUri", notificationUri); userInfo.addMyNotifier(addMap); } View rootView = createView(notificationTitle, notificationMessage, notificationUri); setContentView(rootView); } // 创建通知详细信息界面 @SuppressLint("NewApi") private View createView(final String title, String message, final String uri) { final LinearLayout linearLayout = new LinearLayout(this); scrollView = new ScrollView(this); // linearLayout.setBackgroundColor(0xffeeeeee); Resources res = getResources(); // 设置背景图 Drawable dw = res.getDrawable(R.drawable.bg3); linearLayout.setBackgroundDrawable(dw); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(5, 5, 5, 5); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); linearLayout.setLayoutParams(layoutParams); TextView textTitle = new TextView(this); textTitle.setText(title); textTitle.setTextSize(21); // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); textTitle.setTypeface(Typeface.DEFAULT, Typeface.BOLD); textTitle.setTextColor(0xffffff00); textTitle.setGravity(Gravity.CENTER); titleParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); titleParams.setMargins(5, 5, 5, 10); textTitle.setLayoutParams(titleParams); linearLayout.addView(textTitle); // 首先判断uri,如果uri包含video说明是视频信息,转入视频界面 // 如果是视频信息 if (message.startsWith("传来的是视频")) { Log.i("xiaobingo", "进入视频"); WebView messageDetial = new WebView(this); messageDetial.getSettings().setJavaScriptEnabled(true); messageDetial.getSettings().setAllowFileAccess(true); messageDetial.getSettings().setPluginsEnabled(true); messageDetial.getSettings().setSupportZoom(true); messageDetial.getSettings().setAppCacheEnabled(true); String former = message.split("xiaobingo")[0]; String after = message.split("xiaobingo")[1]; System.out.println("afterString:" + after); int urlStart = former.indexOf("=") + 1; rtmpUrl = former.substring(urlStart); fileName = after; // 视频直播 if (rtmpUrl.contains("live")) { msgEnd = fileName.indexOf(".flv"); fileName = fileName.substring(0, msgEnd); // 直播视频不加后缀 } // 视频点播 else { fileName = "flv:" + fileName; // flv:倒霉熊02.flv } Log.i("xiaobingo", "message是:" + message); Log.i("xiaobingo", "rtmpUrl是:" + rtmpUrl); Log.i("xiaobingo", "fileName:" + fileName); String htmlCode = "<embed " + "type=\"application/x-shockwave-flash\"" + "id=\"player1\" " + "name=\"player1\" " + "src=\"http://push.pkusz.edu.cn" + "/mediaplayer.swf\"" + "width=\"" + mobileWidth + "\"" + " height=\"" + mobileHeight / 2 + "\"" + " flashvars=@FILESRC@" + "allowfullscreen=\"true\"" + "allowscripaccess=\"always\"" + "/> "; Log.i("xiaobingo", "htmlCode:" + htmlCode); bodyHtml = htmlCode; bodyHtml = bodyHtml.replaceAll("@FILESRC@", "\"file=" + fileName + "&streamer=" + rtmpUrl + "\""); messageDetial.loadDataWithBaseURL( "http://127.0.0.1", htmlPre + bodyHtml + htmlPost, "text/html", "UTF-8", null); videoParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); videoParams.setMargins(1, 3, 3, 5); scrollView.setLayoutParams(videoParams); scrollView.addView(messageDetial); } else { TextView textDetails = new TextView(this); textDetails.setText(message); textDetails.setTextSize(17); // textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); textDetails.setTextColor(0xeeffeeee); textDetails.setGravity(Gravity.FILL); contentParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int) (mobileHeightPix * 0.7)); contentParams.setMargins(5, 3, 5, 5); scrollView.setLayoutParams(contentParams); scrollView.addView(textDetails); } linearLayout.addView(scrollView); // 点击详细按钮,连接到url,这里还须保存通知历史记录 Button okButton = new Button(this); okButton.setText("查看详细"); okButton.setTextSize(16); // okButton.setTypeface(Typeface.DEFAULT, Typeface.BOLD); okButton.setTextColor(0xff6699ff); Drawable dr = res.getDrawable(R.drawable.button3); okButton.setBackgroundDrawable(dr); okButton.setOnClickListener( new View.OnClickListener() { public void onClick(View view) { Intent intent; if (uri != null && uri.length() > 0 && (uri.startsWith("http:") || uri.startsWith("https:") || uri.startsWith("tel:") || uri.startsWith("geo:"))) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity"); } else { intent = new Intent().setClassName(callbackActivityPackageName, callbackActivityClassName); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); // intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } NotificationDetailsActivity.this.startActivity(intent); NotificationDetailsActivity.this.finish(); } }); // 回复button事件 final Button btn_response = new Button(this); btn_response.setText("我要留言"); btn_response.setTextSize(16); // btn_response.setTypeface(Typeface.DEFAULT, Typeface.BOLD); btn_response.setTextColor(0xff6699ff); btn_response.setBackgroundDrawable(dr); LinearLayout buttonLayout = new LinearLayout(this); buttonLayout.setGravity(Gravity.CENTER); buttonLayout.addView(okButton); // 添加“查看详细”按钮 buttonLayout.addView(btn_response); // 添加“我要留言”按钮 buttonParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); buttonParams.setMargins(3, 3, 3, 3); buttonLayout.setLayoutParams(buttonParams); // innerLayout.setGravity(1); linearLayout.addView(buttonLayout); // 我要留言事件 final EditText responseText = new EditText(this); responseText.setWidth((int) (mobileWidthPix * 0.6)); Button btn_send = new Button(this); btn_send.setText("留言"); btn_send.setTextSize(16); btn_send.setTypeface(Typeface.DEFAULT, Typeface.BOLD); btn_send.setTextColor(0xff6699ff); btn_send.setBackgroundDrawable(dr); responseLayout = new LinearLayout(this); responseLayout.setGravity(Gravity.CENTER); responseLayout.addView(responseText); responseLayout.addView(btn_send); responseParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int) (mobileHeightPix * 0.12)); responseParams.setMargins(3, 3, 3, 3); responseLayout.setLayoutParams(responseParams); btn_response.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // button点击一次,显示留言区 if (!flag) { contentParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int) (mobileHeightPix * 0.6)); contentParams.setMargins(5, 3, 5, 5); scrollView.setLayoutParams(contentParams); linearLayout.addView(responseLayout); } // button再点击一次,去除留言区 else { contentParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int) (mobileHeightPix * 0.7)); contentParams.setMargins(5, 3, 5, 5); scrollView.setLayoutParams(contentParams); linearLayout.removeView(responseLayout); } flag = !flag; } }); // 发送留言button事件 btn_send.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { String myResponse = responseText.getText().toString(); String androidpnURL = "http://219.223.222.232/bbs-api/?"; /*--拼接POST字符串--*/ StringBuilder parameter = new StringBuilder(); parameter.append("action=newreply"); parameter.append("&tid="); Log.d("notificationUri", "notificationUri is:" + notificationUri); parameter.append(notificationUri.substring(notificationUri.indexOf("&tid=") + 5)); parameter.append("&message="); parameter.append(myResponse); parameter.append("&username=admin&password=123"); // androidpnURL += "action=newreply"; // androidpnURL += "&tid=58&message="; // androidpnURL += myResponse; // androidpnURL += "&username=admin&password=123"; // parameter.append("&androidName=admin&"); // parameter.append(originSharedPrefs.getString(Constants.XMPP_USERNAME, // "未知用户")); // parameter.append("&reply="); // parameter.append(myResponse); /*--End--*/ Log.i("LoginActivity", androidpnURL); String resp = GetPostUtil.send("POST", androidpnURL, parameter); Log.i("LoginActivity", "resp:" + resp); responseText.setText(""); // 清空留言区 } }); // linearLayout.setGravity(Gravity.BOTTOM); return linearLayout; } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); NotificationDetailsActivity.this.finish(); } // protected void onPause() { // super.onPause(); // finish(); // } // // protected void onStop() { // super.onStop(); // finish(); // } // // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // } // // protected void onNewIntent(Intent intent) { // setIntent(intent); // } }
/** * This class is to manage the notificatin service and to load the configuration. * * @author Sehwan Noh ([email protected]) */ public final class ServiceManager { private static final String LOGTAG = LogUtil.makeLogTag(ServiceManager.class); private Context context; private SharedPreferences sharedPrefs; private Properties props; private String version = "0.5.0"; private String apiKey; private String xmppHost; private String xmppPort; private String callbackActivityPackageName; private String callbackActivityClassName; public ServiceManager(Context context) { this.context = context; if (context instanceof Activity) { Log.i(LOGTAG, "Callback Activity..."); Activity callbackActivity = (Activity) context; callbackActivityPackageName = callbackActivity.getPackageName(); callbackActivityClassName = callbackActivity.getClass().getName(); } // apiKey = getMetaDataValue("ANDROIDPN_API_KEY"); // Log.i(LOGTAG, "apiKey=" + apiKey); // // if (apiKey == null) { // // Log.e(LOGTAG, "Please set the androidpn api key in the manifest file."); // // throw new RuntimeException(); // // } props = loadProperties(); apiKey = props.getProperty("apiKey", ""); xmppHost = props.getProperty("xmppHost", "127.0.0.1"); xmppPort = props.getProperty("xmppPort", "5222"); Log.i(LOGTAG, "apiKey=" + apiKey); Log.i(LOGTAG, "xmppHost=" + xmppHost); Log.i(LOGTAG, "xmppPort=" + xmppPort); sharedPrefs = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); Editor editor = sharedPrefs.edit(); editor.putString(Constants.API_KEY, apiKey); editor.putString(Constants.VERSION, version); editor.putString(Constants.XMPP_HOST, xmppHost); editor.putInt(Constants.XMPP_PORT, Integer.parseInt(xmppPort)); editor.putString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, callbackActivityPackageName); editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME, callbackActivityClassName); editor.commit(); // Log.i(LOGTAG, "sharedPrefs=" + sharedPrefs.toString()); } public void startService() { Thread serviceThread = new Thread( new Runnable() { @Override public void run() { Intent intent = NotificationService.getIntent(); context.startService(intent); } }); serviceThread.start(); } public void stopService() { Intent intent = NotificationService.getIntent(); context.stopService(intent); } // private String getMetaDataValue(String name, String def) { // String value = getMetaDataValue(name); // return (value == null) ? def : value; // } // // private String getMetaDataValue(String name) { // Object value = null; // PackageManager packageManager = context.getPackageManager(); // ApplicationInfo applicationInfo; // try { // applicationInfo = packageManager.getApplicationInfo(context // .getPackageName(), 128); // if (applicationInfo != null && applicationInfo.metaData != null) { // value = applicationInfo.metaData.get(name); // } // } catch (NameNotFoundException e) { // throw new RuntimeException( // "Could not read the name in the manifest file.", e); // } // if (value == null) { // throw new RuntimeException("The name '" + name // + "' is not defined in the manifest file's meta data."); // } // return value.toString(); // } private Properties loadProperties() { // InputStream in = null; // Properties props = null; // try { // in = getClass().getResourceAsStream( // "/org/androidpn/client/client.properties"); // if (in != null) { // props = new Properties(); // props.load(in); // } else { // Log.e(LOGTAG, "Could not find the properties file."); // } // } catch (IOException e) { // Log.e(LOGTAG, "Could not find the properties file.", e); // } finally { // if (in != null) // try { // in.close(); // } catch (Throwable ignore) { // } // } // return props; Properties props = new Properties(); try { int id = context.getResources().getIdentifier("androidpn", "raw", context.getPackageName()); props.load(context.getResources().openRawResource(id)); } catch (Exception e) { Log.e(LOGTAG, "Could not find the properties file.", e); // e.printStackTrace(); } return props; } // public String getVersion() { // return version; // } // // public String getApiKey() { // return apiKey; // } public void setNotificationIcon(int iconId) { Editor editor = sharedPrefs.edit(); editor.putInt(Constants.NOTIFICATION_ICON, iconId); editor.commit(); } // public void viewNotificationSettings() { // Intent intent = new Intent().setClass(context, // NotificationSettingsActivity.class); // context.startActivity(intent); // } public static void viewNotificationSettings(Context context) { Intent intent = new Intent().setClass(context, NotificationSettingsActivity.class); context.startActivity(intent); } }
/** * This class is to notify the user of messages with NotificationManager. * * @author Sehwan Noh ([email protected]) */ public class Notifier { private static final String LOGTAG = LogUtil.makeLogTag(Notifier.class); private static final Random random = new Random(System.currentTimeMillis()); private Context context; private SharedPreferences sharedPrefs; private NotificationManager notificationManager; /** Notification构造器 */ NotificationCompat.Builder mBuilder; public Notifier(Context context) { this.context = context; this.sharedPrefs = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE); this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder = new NotificationCompat.Builder(context); } public void notify( String notificationId, String apiKey, String title, String message, String uri, String imageUrl) { Log.d(LOGTAG, "notify()..."); Log.d(LOGTAG, "notificationId=" + notificationId); Log.d(LOGTAG, "notificationApiKey=" + apiKey); Log.d(LOGTAG, "notificationTitle=" + title); Log.d(LOGTAG, "notificationMessage=" + message); Log.d(LOGTAG, "notificationUri=" + uri); if (isNotificationEnabled()) { // Show the toast if (isNotificationToastEnabled()) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } mBuilder .setWhen(System.currentTimeMillis()) // 通知产生的时间,会在通知信息里显示 .setPriority(Notification.PRIORITY_DEFAULT) // 设置该通知优先级 // .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消 .setOngoing( false) // ture,设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接) .setDefaults( Notification .DEFAULT_VIBRATE) // 向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置,使用defaults属性,可以组合: // Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE // permission .setSmallIcon(getNotificationIcon()); mBuilder .setAutoCancel(true) // 点击后让通知将消失 .setContentTitle(title) .setContentText(message) .setTicker(message); // Notification if (isNotificationSoundEnabled()) { mBuilder.setDefaults(Notification.DEFAULT_SOUND); } if (isNotificationVibrateEnabled()) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } mBuilder.setOnlyAlertOnce(true); // Intent intent; // if (uri != null // && uri.length() > 0 // && (uri.startsWith("http:") || uri.startsWith("https:") // || uri.startsWith("tel:") || uri.startsWith("geo:"))) { // intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); // } else { // String callbackActivityPackageName = sharedPrefs.getString( // Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, ""); // String callbackActivityClassName = sharedPrefs.getString( // Constants.CALLBACK_ACTIVITY_CLASS_NAME, ""); // intent = new Intent().setClassName(callbackActivityPackageName, // callbackActivityClassName); // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // } Intent intent = new Intent(context, NotificationDetailsActivity.class); intent.putExtra(Constants.NOTIFICATION_ID, notificationId); intent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey); intent.putExtra(Constants.NOTIFICATION_TITLE, title); intent.putExtra(Constants.NOTIFICATION_MESSAGE, message); intent.putExtra(Constants.NOTIFICATION_URI, uri); intent.putExtra(Constants.NOTIFICATION_IMAGE_URL, imageUrl); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity( context, random.nextInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(contentIntent); notificationManager.notify(random.nextInt(), mBuilder.build()); } else { Log.w(LOGTAG, "Notificaitons disabled."); } } private int getNotificationIcon() { return sharedPrefs.getInt(Constants.NOTIFICATION_ICON, 0); } private boolean isNotificationEnabled() { return sharedPrefs.getBoolean(Constants.SETTINGS_NOTIFICATION_ENABLED, true); } private boolean isNotificationSoundEnabled() { return sharedPrefs.getBoolean(Constants.SETTINGS_SOUND_ENABLED, true); } private boolean isNotificationVibrateEnabled() { return sharedPrefs.getBoolean(Constants.SETTINGS_VIBRATE_ENABLED, true); } private boolean isNotificationToastEnabled() { return sharedPrefs.getBoolean(Constants.SETTINGS_TOAST_ENABLED, false); } }