Service+(Notification+)Thread+HttpPost

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 calling startService(). 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() or stopService(). (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.




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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值