Service+(Notification+)Thread+HttpPost

来源:互联网 发布:微信跳转淘宝app 编辑:程序博客网 时间:2024/05/17 21:06

Intent,同是发出一个toast

Intent intent = new Intent(this, CollectingDataService.class);

Toast.makeText(this, "uploading sensor data to " + serverAddress,                Toast.LENGTH_SHORT).show();


将serverAddress传入intent
 intent.putExtra(NetworkSettingsActivity.INTENT_EXTRA_SEVER_ADDRESS, serverAddress); startService(intent);



onStartCommand()
The system calls this method when another component, such as an activity, requests that the service be started, by callingstartService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() orstopService(). (If you only want to provide binding, you don't need to implement this method.)
onBind()
The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.
onCreate()
The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.
onDestroy()
The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.


  • The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy()returns. Like an activity, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy(). For example, a music playback service could create the thread where the music will be played in onCreate(), then stop the thread in onDestroy().

    The onCreate() and onDestroy() methods are called for all services, whether they're created bystartService() or bindService().

  • The active lifetime of a service begins with a call to either onStartCommand() or onBind(). Each method is handed the Intent that was passed to either startService() or bindService(), respectively.

    If the service is started, the active lifetime ends the same time that the entire lifetime ends (the service is still active even after onStartCommand() returns). If the service is bound, the active lifetime ends whenonUnbind() returns.



package com.liangfeizc.carpairclient.services;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import com.liangfeizc.carpairclient.activities.MyActivity;import com.liangfeizc.carpairclient.network.MyHttpClient;import com.liangfeizc.carpairclient.R;import com.liangfeizc.carpairclient.network.SensorData;import com.liangfeizc.carpairclient.settings.NetworkSettingsActivity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ConnectionPoolTimeoutException;import org.apache.http.message.BasicNameValuePair;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Random;public class CollectingDataService extends Service {    private static final String TAG = "CollectingDataService";    private NotificationManager mNotificationManager;    private ThreadGroup mThreadGrp = new ThreadGroup("ServiceWorker");    private HttpClient mHttpClient;    private String mPostAddress;    @Override    public void onCreate() {        super.onCreate();        Log.v(TAG, "onCreate() called");        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);        mHttpClient = MyHttpClient.getHttpClient();        displayNotificationMessage(getResources().getString(R.string.uploading_data_msg));    }    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        super.onStartCommand(intent, flags, startId);        String serverAddress = intent.getStringExtra(                NetworkSettingsActivity.INTENT_EXTRA_SEVER_ADDRESS);        new Thread(mThreadGrp, new ServiceWorker(serverAddress), "CollectingDataService").start();        return START_STICKY;    }    @Override    public void onDestroy() {        Log.v(TAG, "onDestory called");        mThreadGrp.interrupt();        mNotificationManager.cancelAll();        super.onDestroy();    }    class ServiceWorker implements Runnable {        private String mServerAddress;        public ServiceWorker(String serverAddress) {            mServerAddress = serverAddress;        }        @Override        public void run() {            while (true) {                try {                    HttpPost request = new HttpPost(mServerAddress);                    List<NameValuePair> postParams = new ArrayList<NameValuePair>();                    String data = generateData();                    postParams.add(new BasicNameValuePair("postData", data));                    UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(postParams);                    request.setEntity(formEntiry);                    HttpResponse response = mHttpClient.execute(request);                    Thread.sleep(500);                } catch (InterruptedException e) {                    Log.v(TAG, "Connection Interrupted");                } catch (ConnectionPoolTimeoutException e) {                    Log.v(TAG, "Connection Pool Timeout");                } catch (IOException e) {                    e.printStackTrace();                }            }        }        private String generateData() {            Random rand = new Random();            StringBuffer sb = new StringBuffer("[");            for (int i = 0; i < rand.nextInt(5); i++) {                sb.append(SensorData.generate()).append(",");            }            sb.append(SensorData.generate());            sb.append("]");            return sb.toString();        }    }    private void displayNotificationMessage(String message) {        Notification notification = new Notification(R.drawable.ic_launcher,                message, System.currentTimeMillis());        notification.flags = Notification.FLAG_NO_CLEAR;        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,                new Intent(this, MyActivity.class), 0);        notification.setLatestEventInfo(this, TAG, message, contentIntent);        mNotificationManager.notify(0, notification);    }}




0 0