Intent,同是发出一个toast
Intent intent = new Intent(this, CollectingDataService.class);
Toast.makeText(this, "uploading sensor data to " + serverAddress,
Toast.LENGTH_SHORT).show();
intent.putExtra(NetworkSettingsActivity.INTENT_EXTRA_SEVER_ADDRESS, serverAddress);
startService(intent);
onStartCommand()
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()
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()
onStartCommand()
or
onBind()
). If the service is already running, this method is not called.
onDestroy()
- The entire lifetime of a service happens between the time
onCreate()
is called and the timeonDestroy()
returns. Like an activity, a service does its initial setup inonCreate()
and releases all remaining resources inonDestroy()
. For example, a music playback service could create the thread where the music will be played inonCreate()
, then stop the thread inonDestroy()
.The
onCreate()
andonDestroy()
methods are called for all services, whether they're created bystartService()
orbindService()
. - The active lifetime of a service begins with a call to either
onStartCommand()
oronBind()
. Each method is handed theIntent
that was passed to eitherstartService()
orbindService()
, 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);
}
}