第一行代码-进程服务通知笔记
1. 子线程操作UI的三种方式
a. handler
b. runOnUiThread()
c. asyncTask
c.1 onPreExecute()
c.2 doInBackground(Params...)执行主要任务 调用publishProgress()
c.3 onProgressUpdate(Progress...)进行UI更新
c.4 onPostExecute(Result)
2. 服务的操作
a. 新建类继承Service,重写onBind方法,和其他逻辑操作方法onCreate onStartCommand onDestroy
b. 启动和停止服务
Intent intent=newIntent(this,MyService.class);
startService(intent);
stopService(intent);
c. 绑定服务(用于服务和Activity之间进行联系)
c.1 在服务类中定义一个继承Binder 的内部类 并在OnBind方法中返回定义的内部类对象
c.2 在Activity中bindService(intent,connection,BIND_AUTO_CREATE)解绑unbindService(connection);
c.3 这个connection是ServiceConnection的对象,类中实现的两个方法onServiceDisconnected 和 onServiceConnected(在这个方法中拿到服务中定义的内部类对象,并进行所需的操作)
d. 服务的生命周期
e. 前台服务(源码)
public class LocalService extends Service { private NotificationManager mNM;
// 通知唯一的标识 private int NOTIFICATION = R.string.local_service_started;
public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } }
@Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar. showNotification(); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); return START_NOT_STICKY; }
@Override public void onDestroy() { mNM.cancel(NOTIFICATION); Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); }
@Override public IBinder onBind(Intent intent) { return mBinder; }
private final IBinder mBinder = new LocalBinder();
private void showNotification() { CharSequence text = getText(R.string.local_service_started);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, LocalServiceActivities.Controller.class), 0);
Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.stat_sample) // the status icon .setTicker(text) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label)) // the label of the entry .setContentText(text) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .build();
// Send the notification. mNM.notify(NOTIFICATION, notification); } } |