• Android Service服务-(转)


    Service是Android系统中提供的四大组件之一。它是运行在后台的一种服务,一般声明周期较长,不直接与用户进行交互。

      服务不能自己运行,需要通过调用Context.startService()或Context.bindService()方法启动服务。这两个方法都可以启动Service,但是它们的使用场合有所不同。
        1. 使用startService()方法启用服务,调用者与服务之间没有关连,即使调用者退出了,服务仍然运行。
        如果打算采用Context.startService()方法启动服务,在服务未被创建时,系统会先调用服务的onCreate()方法,接着调用onStart()方法。
        如果调用startService()方法前服务已经被创建,多次调用startService()方法并不会导致多次创建服务,但会导致多次调用onStart()方法。
        采用startService()方法启动的服务,只能调用Context.stopService()方法结束服务,服务结束时会调用onDestroy()方法。
        2. 使用bindService()方法启用服务,调用者与服务绑定在了一起,调用者一旦退出,服务也就终止,大有“不求同时生,必须同时死”的特点。
        onBind()只有采用Context.bindService()方法启动服务时才会回调该方法。该方法在调用者与服务绑定时被调用,当调用者与服务已经绑定,多次调用Context.bindService()方法并不会导致该方法被多次调用。
        采用Context.bindService()方法启动服务时只能调用onUnbind()方法解除调用者与服务解除,服务结束时会调用onDestroy()方法。
     
    这里我采用了第一种方法启动 startService(new Intent(this, LocalService.class));不过首先需要在AndroidManifest.xml文件中注册声明我们新建的Service,在application标签内添加 <service android:name=".LocalService" />即可。
    下面是实现的方法,开启新线程,每隔一分钟从服务器获取消息,若产生消息,则在手机状态栏通知该消息。
    1. public class LocalService extends Service {  
    2.     private static String info = null;  
    3.     private String TAG = "localservice";// 定义打印信息标识  
    4.     private NotificationManager mNM;// 定义状态栏通知  
    5.     private final IBinder mBinder = new LocalBinder();// 实例化LocalBinder  
    6.   
    7.     // public static native void getSqlInfo();  
    8.   
    9.     public class LocalBinder extends Binder {  
    10.         LocalService getService() {  
    11.             return LocalService.this;  
    12.         }  
    13.     }  
    14.   
    15.     public IBinder onBind(Intent intent) {  
    16.         Log.i(TAG, "this is onBind");  
    17.         return mBinder;  
    18.     }  
    19.   
    20.     // 实现创建方法  
    21.     public void onCreate() {  
    22.         Log.i(TAG, "this is onCreate");  
    23.         mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// 获取通知栏管理器  
    24.   
    25.     }  
    26.   
    27.     // 实现开始方法  
    28.     public int onStartCommand(Intent intent, int flags, int startId) {  
    29.         Log.i(TAG, "received start id" + startId + ":" + intent);  
    30.   
    31.         // 开启线程  
    32.         MessageThread messageThread = new MessageThread();  
    33.         messageThread.start();  
    34.   
    35.         return START_STICKY;  
    36.     }  
    37.   
    38.     // 实现销毁方法  
    39.     public void onDestory() {  
    40.         Log.i(TAG, "this is onDestory");  
    41.         mNM.cancel("qqq", 0);  
    42.     }  
    43.   
    44.     // 实现解除bind方法  
    45.     public boolean onUnbind(Intent intent) {  
    46.         Log.i(TAG, "this is onUnbind");  
    47.         return super.onUnbind(intent);  
    48.     }  
    49.   
    50.     private void showNotification(String serverMessage) {  
    51.         int icon = R.drawable.icon; // 通知图标  
    52.         CharSequence tickerText = "local sevice has started" + serverMessage; // 状态栏显示的通知文本提示  
    53.         long when = System.currentTimeMillis(); // 通知产生的时间,会在通知信息里显示  
    54.         // 用上面的属性初始化Nofification// 实例化状态通知  
    55.         Notification notification = new Notification(icon, tickerText, when);  
    56.   
    57.         PendingIntent contentIntent = PendingIntent.getActivity(this, 0,  
    58.                 new Intent(this, HelloPush.class), 0);// 定义通知栏单击时间触发的intent  
    59.   
    60.         notification.defaults |= Notification.DEFAULT_SOUND;// 添加声音  
    61.         // notification.defaults |= Notification.DEFAULT_VIBRATE;// 添加震动  
    62.         notification.defaults |= Notification.DEFAULT_LIGHTS;// 添加LED灯提醒  
    63.         notification.flags = Notification.FLAG_AUTO_CANCEL;// 在通知栏上点击此通知后自动清除此通知  
    64.   
    65.         notification.setLatestEventInfo(this, "Local Service", tickerText,  
    66.                 contentIntent);// 设置该状态栏通知消息的单击事件  
    67.         mNM.notify("qqq", 0, notification);// 通知栏显示该通知  
    68.   
    69.     }  
    70.   
    71.     /** 
    72.      * 从服务器端获取消息 
    73.      *  
    74.      */  
    75.     class MessageThread extends Thread {  
    76.         // 运行状态,下一步骤有大用  
    77.         public boolean isRunning = true;  
    78.   
    79.         @SuppressLint("SimpleDateFormat")  
    80.         public void run() {  
    81.             System.out.println("running++++++++++++++");  
    82.             while (isRunning) {  
    83.                 try {  
    84.   
    85.                     // 获取服务器消息  
    86.                     String serverMessage = getServerMessage();  
    87.   
    88.                     SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");  
    89.                     Date curDate = new Date(System.currentTimeMillis());// 获取当前时间  
    90.                     String str = formatter.format(curDate);  
    91.                     System.out.println("++++++++++++" + str);// &&str=="08:00"  
    92.                     if (serverMessage != null && !"".equals(serverMessage)  
    93.                     // &&"15:00".equalsIgnoreCase(str)  
    94.                     ) {  
    95.                         showNotification(serverMessage);  
    96.                     }  
    97.                     // 休息1分钟  
    98.                     System.out.println("sleeping now+++++");  
    99.                     Thread.sleep(60000);  
    100.                     System.out.println("sleep ended+++++");  
    101.                 } catch (InterruptedException e) {  
    102.                     System.out.println("thread sleep error++++");  
    103.                     e.printStackTrace();  
    104.                 }  
    105.             }  
    106.         }  
    107.     }  
    108.   
    109.     /** 
    110.      * @return 返回服务器要推送的消息,否则如果为空的话,不推送 
    111.      */  
    112.     public String getServerMessage() {  
    113.         System.out.println("getServerMessage++++++++");  
    114.         info = null;  
    115.         // getSqlInfo();  
    116.         // getSql();  
    117.         info = connecting();  
    118.         System.out.println("getServerMessage+++++++" + info);  
    119.         return info;  
    120.     }  
    121.   
    122.     // public static int ReturnInfo(final String title) {  
    123.     // System.out.println("ReturnInfo+++++++++" + title);  
    124.     // info = title;  
    125.     // return 1;  
    126.     // }  
    127.     //  
    128.     // public void getSql() {  
    129.     // try {  
    130.     // String url = "jdbc:mysql://192.168.1.104:80/test";  
    131.     // String user = "root";  
    132.     // String pwd = "";  
    133.     //  
    134.     // // 加载驱动,这一句也可写为:Class.forName("com.mysql.jdbc.Driver");  
    135.     // Class.forName("com.mysql.jdbc.Driver").newInstance();  
    136.     // // 建立到MySQL的连接  
    137.     // Connection conn = DriverManager.getConnection(url, user, pwd);  
    138.     //  
    139.     // // 执行SQL语句  
    140.     // java.sql.Statement stmt = conn.createStatement();// 创建语句对象,用以执行sql语言  
    141.     // ResultSet rs = stmt.executeQuery("select * from push where id = 1");  
    142.     //  
    143.     // // 处理结果集  
    144.     // while (rs.next()) {  
    145.     // String name = rs.getString("name");  
    146.     // info = name;  
    147.     // System.out.println(name);  
    148.     // }  
    149.     // rs.close();// 关闭数据库  
    150.     // conn.close();  
    151.     // } catch (Exception ex) {  
    152.     // System.out.println("Error : " + ex.toString());  
    153.     // }  
    154.     // }  
    155.   
    156.     public String connecting() {  
    157.         /* 存放http请求得到的结果 */  
    158.         String result = "";  
    159.         // String ss = null;  
    160.         String name = null;  
    161.   
    162.         /* 将要发送的数据封包 */  
    163.         ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
    164.         nameValuePairs.add(new BasicNameValuePair("id", "1"));  
    165.   
    166.         InputStream is = null;  
    167.         // http post  
    168.         try {  
    169.             /* 创建一个HttpClient的一个对象 */  
    170.             HttpClient httpclient = new DefaultHttpClient();  
    171.   
    172.             /* 创建一个HttpPost的对象 */  
    173.             HttpPost httppost = new HttpPost(  
    174.                     "http://192.168.1.104:80/ying/yy.php");  
    175.   
    176.             /* 设置请求的数据 */  
    177.             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
    178.   
    179.             /* 创建HttpResponse对象 */  
    180.             HttpResponse response = httpclient.execute(httppost);  
    181.   
    182.             /* 获取这次回应的消息实体 */  
    183.             HttpEntity entity = response.getEntity();  
    184.   
    185.             /* 创建一个指向对象实体的数据流 */  
    186.             is = entity.getContent();  
    187.         } catch (Exception e) {  
    188.             System.out.println("Connectiong Error");  
    189.         }  
    190.         // convert response to string  
    191.         try {  
    192.             BufferedReader reader = new BufferedReader(new InputStreamReader(  
    193.                     is, "iso-8859-1"), 8);  
    194.             StringBuilder sb = new StringBuilder();  
    195.             String line = null;  
    196.             while ((line = reader.readLine()) != null) {  
    197.                 sb.append(line + "/n");  
    198.             }  
    199.             is.close();  
    200.   
    201.             result = sb.toString();  
    202.             System.out.println("get = " + result);  
    203.         } catch (Exception e) {  
    204.             System.out.println("Error converting to String");  
    205.         }  
    206.   
    207.         // parse json data  
    208.         try {  
    209.             /* 从字符串result创建一个JSONArray对象 */  
    210.             JSONArray jArray = new JSONArray(result);  
    211.   
    212.             for (int i = 0; i < jArray.length(); i++) {  
    213.                 JSONObject json_data = jArray.getJSONObject(i);  
    214.                 System.out.println("Success");  
    215.                 System.out.println("result " + json_data.toString());  
    216.                 // ct_id=json_data.getInt("id");  
    217.                 name = json_data.getString("name");  
    218.                 // if (i == 0) {  
    219.                 // ss = json_data.toString();  
    220.                 // } else {  
    221.                 // ss += json_data.toString();  
    222.                 // }  
    223.             }  
    224.         } catch (JSONException e) {  
    225.             System.out.println("Error parsing json");  
    226.         }  
    227.         return name;  
    228.     }  
    229. }  
    下面是php代码
    1. <?php  
    2. require_once("conn.php");  
    3. session_start();  
    4.   
    5. $q=mysql_query("SELECT name FROM push WHERE id='".$_REQUEST['id']."'");  
    6. while($e=mysql_fetch_assoc($q))  
    7.         $output[]=$e;   
    8. print(json_encode($output));   
    9. mysql_close();  
    10. ?>  


  • 相关阅读:
    那些年读过的书《Java并发编程实战》和《Java并发编程的艺术》三、任务执行框架—Executor框架小结
    那些年读过的书《Java并发编程实战》二、如何设计线程安全类
    那些年读过的书《Java并发编程实战》一、构建线程安全类和并发应用程序的基础
    重读《深入理解Java虚拟机》七、探究Java内存模型
    重读《深入理解Java虚拟机》六、Java泛型 VS C#泛型 (伪泛型 VS 真泛型)
    重读《深入理解Java虚拟机》五、虚拟机如何执行字节码?程序方法如何被执行?虚拟机执行引擎的工作机制
    重读《深入理解Java虚拟机》四、虚拟机如何加载Class文件
    input 文本框禁止输入表情
    win7右下角无线网图标显示未连接,但是实际上已连接上,也能上网
    history.back(-1)和history.go(-1)的区别
  • 原文地址:https://www.cnblogs.com/manmanlu/p/3808567.html
Copyright © 2020-2023  润新知