android Service

默认UI线程

生命周期

IntentService 单线程执行 onHandleIntent()

绑定通信

public class MyService extends Service {  
  
    private MyBinder mBinder = new MyBinder();  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        return super.onStartCommand(intent, flags, startId);  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
    }  
  
    @Override  
    public IBinder onBind(Intent intent) {  
        return mBinder;  
    }  
  
    class MyBinder extends Binder {  
  
        public void startDownload() {  
            Log.d("MyService", "startDownload() executed");  
            // 执行具体的下载任务  
        }  
  
    }  
  
}
       
public class MainActivity extends Activity{  
   
    private MyService.MyBinder myBinder;  
  
    private ServiceConnection connection = new ServiceConnection() { 
  
        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            myBinder = (MyService.MyBinder) service;  
            myBinder.startDownload();  
        }  
        
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
        }
    };  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) { 
       
        Intent intent = new Intent(this, MyService.class);  
        //startService(intent);
        //stopService(intent); 
        bindService(intent, connection, BIND_AUTO_CREATE); 
        //unbindService(connection);
    }  
}

前台Service

public class MyService extends Service { 
  
    private MyBinder mBinder = new MyBinder();  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Notification notification = new Notification(R.drawable.ic_launcher,  
                "有通知到来", System.currentTimeMillis());  
        Intent notificationIntent = new Intent(this, MainActivity.class);  
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,  
                notificationIntent, 0);  
        notification.setLatestEventInfo(this, "这是通知的标题", "这是通知的内容",  
                pendingIntent);  
        startForeground(1, notification);  
    }  
  
    .........  
  
}

给用户发送通知

一旦运行,service可以使用 Toast通知Toast Notifications)或 状态条通知(Status Bar Notifications)通知用户事件。