public class LocalService extends Service {
private static String info = null;
private String TAG = "localservice";// 定义打印信息标识
private NotificationManager mNM;// 定义状态栏通知
private final IBinder mBinder = new LocalBinder();// 实例化LocalBinder
// public static native void getSqlInfo();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
public IBinder onBind(Intent intent) {
Log.i(TAG, "this is onBind");
return mBinder;
}
// 实现创建方法
public void onCreate() {
Log.i(TAG, "this is onCreate");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 获取通知栏管理器
}
// 实现开始方法
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "received start id" + startId + ":" + intent);
// 开启线程
MessageThread messageThread = new MessageThread();
messageThread.start();
return START_STICKY;
}
// 实现销毁方法
public void onDestory() {
Log.i(TAG, "this is onDestory");
mNM.cancel("qqq", 0);
}
// 实现解除bind方法
public boolean onUnbind(Intent intent) {
Log.i(TAG, "this is onUnbind");
return super.onUnbind(intent);
}
private void showNotification(String serverMessage) {
int icon = R.drawable.icon; // 通知图标
CharSequence tickerText = "local sevice has started" + serverMessage; // 状态栏显示的通知文本提示
long when = System.currentTimeMillis(); // 通知产生的时间,会在通知信息里显示
// 用上面的属性初始化Nofification// 实例化状态通知
Notification notification = new Notification(icon, tickerText, when);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, HelloPush.class), 0);// 定义通知栏单击时间触发的intent
notification.defaults |= Notification.DEFAULT_SOUND;// 添加声音
// notification.defaults |= Notification.DEFAULT_VIBRATE;// 添加震动
notification.defaults |= Notification.DEFAULT_LIGHTS;// 添加LED灯提醒
notification.flags = Notification.FLAG_AUTO_CANCEL;// 在通知栏上点击此通知后自动清除此通知
notification.setLatestEventInfo(this, "Local Service", tickerText,
contentIntent);// 设置该状态栏通知消息的单击事件
mNM.notify("qqq", 0, notification);// 通知栏显示该通知
}
/**
* 从服务器端获取消息
*
*/
class MessageThread extends Thread {
// 运行状态,下一步骤有大用
public boolean isRunning = true;
@SuppressLint("SimpleDateFormat")
public void run() {
System.out.println("running++++++++++++++");
while (isRunning) {
try {
// 获取服务器消息
String serverMessage = getServerMessage();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String str = formatter.format(curDate);
System.out.println("++++++++++++" + str);// &&str=="08:00"
if (serverMessage != null && !"".equals(serverMessage)
// &&"15:00".equalsIgnoreCase(str)
) {
showNotification(serverMessage);
}
// 休息1分钟
System.out.println("sleeping now+++++");
Thread.sleep(60000);
System.out.println("sleep ended+++++");
} catch (InterruptedException e) {
System.out.println("thread sleep error++++");
e.printStackTrace();
}
}
}
}
/**
* @return 返回服务器要推送的消息,否则如果为空的话,不推送
*/
public String getServerMessage() {
System.out.println("getServerMessage++++++++");
info = null;
// getSqlInfo();
// getSql();
info = connecting();
System.out.println("getServerMessage+++++++" + info);
return info;
}
// public static int ReturnInfo(final String title) {
// System.out.println("ReturnInfo+++++++++" + title);
// info = title;
// return 1;
// }
//
// public void getSql() {
// try {
// String url = "jdbc:mysql://192.168.1.104:80/test";
// String user = "root";
// String pwd = "";
//
// // 加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// // 建立到MySQL的连接
// Connection conn = DriverManager.getConnection(url, user, pwd);
//
// // 执行SQL语句
// java.sql.Statement stmt = conn.createStatement();// 创建语句对象,用以执行sql语言
// ResultSet rs = stmt.executeQuery("select * from push where id = 1");
//
// // 处理结果集
// while (rs.next()) {
// String name = rs.getString("name");
// info = name;
// System.out.println(name);
// }
// rs.close();// 关闭数据库
// conn.close();
// } catch (Exception ex) {
// System.out.println("Error : " + ex.toString());
// }
// }
public String connecting() {
/* 存放http请求得到的结果 */
String result = "";
// String ss = null;
String name = null;
/* 将要发送的数据封包 */
ArrayList nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("id", "1"));
InputStream is = null;
// http post
try {
/* 创建一个HttpClient的一个对象 */
HttpClient httpclient = new DefaultHttpClient();
/* 创建一个HttpPost的对象 */
HttpPost httppost = new HttpPost(
"http://192.168.1.104:80/ying/yy.php");
/* 设置请求的数据 */
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* 创建HttpResponse对象 */
HttpResponse response = httpclient.execute(httppost);
/* 获取这次回应的消息实体 */
HttpEntity entity = response.getEntity();
/* 创建一个指向对象实体的数据流 */
is = entity.getContent();
} catch (Exception e) {
System.out.println("Connectiong Error");
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
is.close();
result = sb.toString();
System.out.println("get = " + result);
} catch (Exception e) {
System.out.println("Error converting to String");
}
// parse json data
try {
/* 从字符串result创建一个JSONArray对象 */
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
System.out.println("Success");
System.out.println("result " + json_data.toString());
// ct_id=json_data.getInt("id");
name = json_data.getString("name");
// if (i == 0) {
// ss = json_data.toString();
// } else {
// ss += json_data.toString();
// }
}
} catch (JSONException e) {
System.out.println("Error parsing json");
}
return name;
}
}
下面是php代码