标签:des android class blog code java
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" />即可。
下面是实现的方法,开启新线程,每隔一分钟从服务器获取消息,若产生消息,则在手机状态栏通知该消息。
- public class LocalService extends Service {
- private static String info = null;
- private String TAG = "localservice";
- private NotificationManager mNM;
- private final IBinder mBinder = new LocalBinder();
-
-
-
- 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);
- }
-
-
- 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();
-
- Notification notification = new Notification(icon, tickerText, when);
-
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, HelloPush.class), 0);
-
- notification.defaults |= Notification.DEFAULT_SOUND;
-
- notification.defaults |= Notification.DEFAULT_LIGHTS;
- 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);
- if (serverMessage != null && !"".equals(serverMessage)
-
- ) {
- showNotification(serverMessage);
- }
-
- System.out.println("sleeping now+++++");
- Thread.sleep(60000);
- System.out.println("sleep ended+++++");
- } catch (InterruptedException e) {
- System.out.println("thread sleep error++++");
- e.printStackTrace();
- }
- }
- }
- }
-
-
- public String getServerMessage() {
- System.out.println("getServerMessage++++++++");
- info = null;
-
-
- info = connecting();
- System.out.println("getServerMessage+++++++" + info);
- return info;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public String connecting() {
-
- String result = "";
-
- String name = null;
-
-
- ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
- nameValuePairs.add(new BasicNameValuePair("id", "1"));
-
- InputStream is = null;
-
- try {
-
- HttpClient httpclient = new DefaultHttpClient();
-
-
- HttpPost httppost = new HttpPost(
- "http://192.168.1.104:80/ying/yy.php");
-
-
- httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
-
-
- HttpResponse response = httpclient.execute(httppost);
-
-
- HttpEntity entity = response.getEntity();
-
-
- is = entity.getContent();
- } catch (Exception e) {
- System.out.println("Connectiong Error");
- }
-
- 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");
- }
-
-
- try {
-
- 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());
-
- name = json_data.getString("name");
-
-
-
-
-
- }
- } catch (JSONException e) {
- System.out.println("Error parsing json");
- }
- return name;
- }
- }
下面是php代码
- <?php
- require_once("conn.php");
- session_start();
-
- $q=mysql_query("SELECT name FROM push WHERE id=‘".$_REQUEST[‘id‘]."‘");
- while($e=mysql_fetch_assoc($q))
- $output[]=$e;
- print(json_encode($output));
- mysql_close();
- ?>
Android Service服务-(转),布布扣,bubuko.com
Android Service服务-(转)
标签:des android class blog code java
原文地址:http://www.cnblogs.com/manmanlu/p/3808567.html